Physical computing ︰《四》 Serial Port ︰ 2. 讀碼學寫

180px-Sillysymphonies-uglyducking1939

220px-Mute_Swan_Cygnets_detail

 

辛棄疾‧醜奴兒

少年不識愁滋味,
愛上層樓,愛上層樓。
為賦新詞強說愁。

而今識盡愁滋味,
欲說還休,欲說還休。
卻道天涼好個秋。

在《 λ 運算︰概念導引《四》》一文中,我們提到了竿影測時的『華表』或許淵源於『仿生』的脛骨。『模仿』的學習方法,就如《何謂寫程式?!》所說的︰

古今文人經由唸『好文章』來學寫『文章』;正像是今天透過讀『好程式』開始設計『程式』一樣,使用適當的『程式庫』 library ,就是『出典』的吧!所以何不《吃著魚釣魚!!有何不可?》的呢!!

Minicom 』是一個 Linux 上『終端機』模擬軟體,據 WiKi 上講︰

A common use for Minicom is when setting up a remote serial console, perhaps as a last resort to access a computer if the LAN is down.

曾經是 PC + Modem + Netscape 上網際網路衝浪,古早有 Mainframe + Terminal ,從應用的角度來看,序列埠可以說是軟硬體『常青樹』的吧!

Stdstreams-notitle.svg
終端機 text terminal 

220px-Analogue_modem_-_acoustic_coupler
數據機 Modem

樹莓派基金會大力推動 python 語言, python 上有一個著名的 pyserial 的序列埠程式庫,現今的版本是 v2.7 ,在 raspbian 裡可以這樣安裝︰

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python-pip
sudo pip install pyserial

# 簡易終端機範例
pi@raspberrypi ~ $ which miniterm.py
/usr/bin/miniterm.py

# v2.7 版 Source Code
pi@raspberrypi ~ $ more /usr/bin/miniterm.py

#!/usr/bin/python

# Very simple serial terminal
# (C)2002-2009 Chris Liechti <cliechti@gmx.net>

# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
# done), received characters are displayed as is (or escaped trough pythons
# repr, useful for debug purposes)

import sys, os, serial, threading

EXITCHARCTER = '\x1d' # GS/CTRL+]
MENUCHARACTER = '\x14' # Menu: CTRL+T

def key_description(character):
"""generate a readable description for a key"""
ascii_code = ord(character)
if ascii_code < 32:
return 'Ctrl+%c' % (ord('@') + ascii_code)
else:
return repr(character)
--More--(2%)
……

它裡頭附有一個『 /usr/bin/miniterm.py 』之簡單終端機程式,可以當作『序列埠』程式的『學習範本』,更由於 python 是互動式的『解譯器』,下述 v2.2 版本的程式之簡短,相信讀者自能從

python miniterm-v2.2.py -p /dev/ttyUSB0 -b 115200 

體會『讀寫』程式的吧!!

#!/usr/bin/env python

# Very simple serial terminal
# (C)2002-2004 Chris Liechti <cliecht@gmx.net>

# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
# done), received characters are displayed as is (or as trough pythons
# repr, useful for debug purposes)
# Baudrate and echo configuartion is done through globals
import sys, os, serial, threading, getopt

EXITCHARCTER = ‘\x04’ #ctrl+D

#first choose a platform dependant way to read single characters from the console
if os.name == ‘nt’:
import msvcrt
def getkey():
while 1:
if echo:
z = msvcrt.getche()
else:
z = msvcrt.getch()
if z == ‘\0’ or z == ‘\xe0’: #functions keys
msvcrt.getch()
else:
if z == ‘\r’:
return ‘\n’
return z

elif os.name == ‘posix’:
import termios, sys, os
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
new[6][termios.VMIN] = 1
new[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, new)
s = ” # We’ll save the characters typed and add them to the pool.
def getkey():
c = os.read(fd, 1)
#~ c = sys.stdin.read(1)
if echo: sys.stdout.write(c); sys.stdout.flush()
return c
def clenaup_console():
termios.tcsetattr(fd, termios.TCSAFLUSH, old)
sys.exitfunc = clenaup_console #terminal modes have to be restored on exit…

else:
raise “Sorry no implementation for your platform (%s) available.” % sys.platform

CONVERT_CRLF = 2
CONVERT_CR = 1
CONVERT_LF = 0

def reader():
“””loop forever and copy serial->console”””
while 1:
data = s.read()
if repr_mode:
sys.stdout.write(repr(data)[1:-1])
else:
sys.stdout.write(data)
sys.stdout.flush()

def writer():
“””loop and copy console->serial until EOF character is found”””
while 1:
c = getkey()
if c == EXITCHARCTER:
break #exit app
elif c == ‘\n’:
if convert_outgoing == CONVERT_CRLF:
s.write(‘\r\n’) #make it a CR+LF
elif convert_outgoing == CONVERT_CR:
s.write(‘\r’) #make it a CR
elif convert_outgoing == CONVERT_LF:
s.write(‘\n’) #make it a LF
else:
s.write(c) #send character
#print a short help message
def usage():
sys.stderr.write(“””USAGE: %s [options]
Miniterm – A simple terminal program for the serial port.

options:
-p, –port=PORT: port, a number, default = 0 or a device name
-b, –baud=BAUD: baudrate, default 9600
-r, –rtscts: enable RTS/CTS flow control (default off)
-x, –xonxoff: enable software flow control (default off)
-e, –echo: enable local echo (default off)
-c, –cr: do not send CR+LF, send CR only
-n, –newline: do not send CR+LF, send LF only
-D, –debug: debug received data (escape nonprintable chars)

“”” % (sys.argv[0], ))

if __name__ == ‘__main__’:
#initialize with defaults
port = 0
baudrate = 9600
echo = 0
convert_outgoing = CONVERT_CRLF
rtscts = 0
xonxoff = 0
repr_mode = 0

#parse command line options
try:
opts, args = getopt.getopt(sys.argv[1:],
“hp:b:rxecnD”,
[“help”, “port=”, “baud=”, “rtscts”, “xonxoff”, “echo”,
“cr”, “newline”, “debug”]
)
except getopt.GetoptError:
# print help information and exit:
usage()
sys.exit(2)

for o, a in opts:
if o in (“-h”, “–help”): #help text
usage()
sys.exit()
elif o in (“-p”, “–port”): #specified port
try:
port = int(a)
except ValueError:
port = a
elif o in (“-b”, “–baud”): #specified baudrate
try:
baudrate = int(a)
except ValueError:
raise ValueError, “Baudrate must be a integer number, not %r” % a
elif o in (“-r”, “–rtscts”):
rtscts = 1
elif o in (“-x”, “–xonxoff”):
xonxoff = 1
elif o in (“-e”, “–echo”):
echo = 1
elif o in (“-c”, “–cr”):
convert_outgoing = CONVERT_CR
elif o in (“-n”, “–newline”):
convert_outgoing = CONVERT_LF
elif o in (“-D”, “–debug”):
repr_mode = 1

#open the port
try:
s = serial.Serial(port, baudrate, rtscts=rtscts, xonxoff=xonxoff)
except:
sys.stderr.write(“Could not open port\n”)
sys.exit(1)
sys.stderr.write(“— Miniterm — type Ctrl-D to quit\n”)
#start serial->console thread
r = threading.Thread(target=reader)
r.setDaemon(1)
r.start()
#and enter console->serial loop
writer()

sys.stderr.write(“\n— exit —\n”)

 

此致『 K 程式』更有興趣的讀者︰

pyserial/serial/tools/miniterm.py 》;

需要文件?

Welcome to pySerial’s documentation 》。

 

 

 

 

Physical computing ︰《四》 Serial Port ︰ 1. 開宗明義

假使從 RS-232Null ModemUARTSerial PortSystem Console 之發展與變遷的歷史來看,可以知道許多典型『應用』和週邊『裝置』興替的過程,即使在今天也都還非常『有用』。兩台電腦間簡單的『 null modem 』虛數據機連線,可以構成很好的『軟體學習』環境。事實上只有一個

樹莓派』也可以玩些不一樣的事情。由於我們將談談『序列埠』在『軟體學習』上的一些想法, 在此並不介紹基本的 Serial Port 之點點滴滴,特於此篇列出一些參考鏈結︰

Raspberry Pi Serial Port

RPi Serial Connection

What is AMA in /dev/ttyAMA0

Lesson 5. Using a Console Cable ── Adafruit’s Raspberry Pi

How To: Use Minicom on Linux for Serial Port Comunication

希望讀者能夠自行閱讀。

Loop Back System Console 系統主控台繞回接法︰

Pin 6 GND黑色線
Pin 8 TXD白色線
Pin 10 RXD綠色線
紅色線 +5V 不接

USB 連接頭接回『樹莓派』。

139_G_1373091551948

# 登入樹莓派
ssh -l pi IP_ADDR

# 安裝 minicom
sudo apt-get install minicom

# 連接系統主控台
minicom -b 115200 -o -D /dev/ttyUSB0

 

這樣的環境有用嗎?又可以作些什麼用呢??

 

 

 

Physical computing ︰《三》 GPIO 溯源《下》

易經》第四十八卦‧水風井

井:改邑不改井,無喪無得,往來井井。汔至,亦未繘井,羸其瓶,凶。

彖曰巽乎水而上水,井﹔井養而不窮也。改邑不改井,乃以剛中也。汔至亦未繘井,未有功也。 羸其瓶,是以凶也。

象曰:木上有水,井﹔君子以勞民勸相。

初六:井泥不食,舊井無禽。
象曰:井泥不食,下也。 舊井無禽,時舍也。

九二:井谷射鮒,瓮敝漏。
象曰:井谷射鮒,無與也。

九三:井渫不食,為我民惻,可用汲,王明,并受其福。
象曰:井渫不食,行惻也。 求王明,受福也。

六四:井甃,無咎。
象曰:井甃無咎,修井也。

九五:井冽,寒泉食。
象曰:寒泉之食,中正也。

上六:井收勿幕,有孚無吉。
象曰元吉在上,大成也。

』曾是『水源地』,人們的『聚集處』,意見交流之所,因此古有改邑不改井之說。

家釀電腦俱樂部』 Homebrew Computer Club 的第一次聚會,啟發催生了『 Apple I』!就是今天那個大名鼎鼎『蘋果公司』!!果真是所謂的『集賢社火』的精神。

禮記‧學記》有言曰︰

大學之法,禁於未發之謂豫,當其可之謂時,不陵節而施之謂孫,相觀而善之謂摩。此四者,教之所由興也。

發然後禁,則扞格而不勝;時過然後學,則勤苦而難成;雜施而不孫,則壞亂而不修;獨學而無友,則孤陋而寡聞燕朋逆其師,燕辟廢其學。此六者,教之所由廢也。

Invitation_to_First_Homebrew_Computer_Club_meeting

Homebrew Computer Club
第一次會議
March 5, 7 pm 1975

240px-Apple_I_Computer

史蒂芬‧蓋瑞‧沃茲尼克
Stephen Gary Wozniak
發明 Apple I

過去嘗聽聞網路上有人講︰你的樹莓派是不是『 Made in U.K. 』的迷思!藉此摘要《 RPi Hardware History 》一文,略作說明︰

pi@raspberrypi ~ $ cat /proc/cpuinfo 
processor	: 0
model name	: ARMv6-compatible processor rev 7 (v6l)
Features	: swp half thumb fastmult vfp edsp java tls 
CPU implementer	: 0x41
CPU architecture: 7
CPU variant	: 0x0
CPU part	: 0xb76
CPU revision	: 7

Hardware	: BCM2708
# 硬體版本 000d,表示中國大陸 Egoman Q4 2012 製造
Revision	: 000d
Serial		: 0000000019eecb9c

這是一塊『樹莓派』 B 版/512MB 剛出來時的『綠色』板子,之後『樹莓派基金會』授權『 Egoman 』生產『紅色』板子,然而正如《 Red Pi at night 》所說,作者也沒有見過。既然主要『電路』、『 PCB 』等等都是『樹莓派基金會』所為,『 Made in China 』真能夠有多大差異??各個硬體修訂版本請參閱下表︰

RevisionRelease
Date
ModelPCB
Revision
MemoryNotes
BetaQ1 2012B (Beta)?256MBBeta Board
0002Q1 2012B1.0256MB
0003Q3 2012B (ECN0001)1.0256MBFuses mod and D14 removed
0004Q3 2012B2.0256MBMfg by Sony
0005Q4 2012B2.0256MBMfg by Qisda
0006Q4 2012B2.0256MBMfg by Egoman
0007Q1 2013A2.0256MBMfg by Egoman
0008Q1 2013A2.0256MBMfg by Sony
0009Q1 2013A2.0256MBMfg by Qisda
000dQ4 2012B2.0512MBMfg by Egoman
000eQ4 2012B2.0512MBMfg by Sony
000fQ4 2012B2.0512MBMfg by Qisda
0010Q3 2014B+1.0512MBMfg by Sony
0011Q2 2014Compute Module1.0512MBMfg by Sony
0012Q4 2014A+1.0256MBMfg by Sony

raspberry-pi-circuit-gpio-input-pins

當然要用樹莓派釀製佳餚,那就一定得了解一些 GPIO 『電性規格』 Electrical Specifications ,在此介紹一篇『 Mosaic Documentation Web 』上『電性規格』的整理文章。

以及樹莓派基本『 GPIO 界面電路』,作為一個 DIY 起點。

 

 

 

 

Physical computing ︰《三》 GPIO 溯源《中》

小王子‧IX

我想小王子大概是利用一群候鳥遷徙的機會跑出来的。在他出發的那天早上, 他把他的星球收拾得整整齊齊,把它上頭的活火山打掃得乾乾淨淨。── 他有两個活火山,早上熱早點很方便。他還有一座死火山,他也把它打掃乾淨。他想, 說不定它還會活動!打掃乾淨了,它們就可以慢慢地有規律的燃燒,而不會突 然爆發。火山爆發就像煙囪裡的火焰一樣。當然,在我們地球上我們人太小,不 能打掃火山,所以火山给我們帶來很多很多麻煩。

xwz23

小王子還把剩下的最後幾棵猴面包樹苗全拔了。他有點憂傷。他以為他再也 不會回来了。這天,這些家常活使他感到特别親切。當他最后一次澆花時,準備 把她好好珍藏起来。他發覺自己要哭出來。

“再見了。”他對花ㄦ說道。

可是花ㄦ没有回答他。

“再見了。”他又說了一遍。

花ㄦ咳嗽了一陣。但並不是由於感冒。

她终於對他說道:“我方才真蠢。請你原諒我。希望你能幸福。” 花ㄦ對他毫不抱怨,他感到很驚訝。他舉著罩子,不知所措地佇立在那裡。 他不明白她為什麼會這樣温柔恬静。“的確,我愛你。”花ㄦ對他說

xwz24

道:“但由於我的過錯,你一點也没有理會。 這絲毫不重要。不過,你也和我一樣的蠢。希望你今後能幸福。把罩子放在一邊 吧,我用不著它了。”

“要是風來了怎麽辦?”

“我的感冒並不那麽重……夜晚的凉風對我倒有好處。我是一朵花。”

“要是有蟲子野獸呢?……”

“我要是想認識蝴蝶,經不起两三隻尺蠖是不行的。據說這是很美的。不然 還有誰來看我呢?你就要到遠處去了。至於說大動物,我並不怕,我有爪子。”

於是,她天真地顯露出她那四根刺,隨後又說道:
“别這麼磨蹭了。真煩人!你既然决定離開這兒,那麽,快走吧!”

她是怕小王子看見她在哭。她是一朵非常驕傲的花……

 

─── 先生接著說︰【 其他 BCM-GPIO 】先在此忽略。

學生剛想開口問︰先生,五十四和十七差很多……,一陣風吹來,只見︰ X

附近的宇宙中,還有 325、326、327、328、329、330 等幾顆小行星。他就開始訪問這幾顆星球,想在那裡找點事幹,並且學習學習。……

祇聞那學生咳嗽了幾聲………

,怎知先生早已瞧見,講︰為什麼是五十四呢?既然從 0 到 54 不是五十五嗎??

學生︰★★★………

連『五四刪』都不知道,還敢一心以為鴻鵠將至的哩!!! ───

 

GPIO Sysfs Interface for Userspace
==================================

Platforms which use the “gpiolib” implementors framework may choose to configure a sysfs user interface to GPIOs. This is different from the debugfs interface, since it provides control over GPIO direction and value instead of just showing a gpio state summary. Plus, it could be present on production systems without debugging support. 【樹莓派上使用 sysfs

Given appropriate hardware documentation for the system, userspace could know for example that GPIO #23 controls the write protect line used to protect boot loader segments in flash memory. System upgrade procedures may need to temporarily remove that protection, first importing a GPIO, then changing its output state, then updating the code before re-enabling the write protection. In normal use, GPIO #23 would never be touched, and the kernel would have no need to know about it. 一般性與特殊性分開

Again depending on appropriate hardware documentation, on some systems userspace GPIO can be used to determine system configuration data that standard kernels won’t know about. And for some tasks, simple userspace GPIO drivers could be all that the system really needs. 【標準化和客製化別立

Note that standard kernel drivers exist for commonLEDs and Buttons” GPIO tasks: “leds-gpio” and “gpio_keys“, respectively. Use those instead of talking directly to the GPIOs; they integrate with kernel frameworks better than your userspace code could.通用性為上

Paths in Sysfs
————–
There are three kinds of entry入口】in /sys/class/gpio:

Control interfaces控制界面】used to get userspace control over GPIOs;

GPIOs晶片上的接腳】themselves; and

GPIO controllersGPIO 控制器】(“gpio_chip” instances).

That’s in addition to standard files including the “device” symlink.

The control interfacesGPIO 控制器】are write-only 【只寫】:

/sys/class/gpio/

export” 【導出】 … Userspace may ask the kernel to export control of a GPIO to userspace by writing its number to this file. 【在使用者空間建立晶片編號 GPIO□□ 接腳的控制特殊檔界面

Example: “echo 19 > export” will create a “gpio19” node for GPIO #19, if that’s not requested by kernel code. 不是核心已使用的

unexport” 【結束導出】… Reverses the effect of exporting to userspace. 【關閉在使用者空間已經開啟之晶片編號 GPIO□□ 接腳的控制特殊檔界面

Example: “echo 19 > unexport” will remove a “gpio19” node exported using the “export” file.

GPIO signals have paths like /sys/class/gpio/gpio42/ (for GPIO #42)
and have the following read/write attributes讀寫屬性】:

/sys/class/gpio/gpioN/

direction” 【輸入或輸出】… reads as either “in” or “out“. This value may normally be written. Writing as “out” defaults to initializing the value as low. To ensure glitch free operation, values “low” and “high” may be written to configure the GPIO as an output with that initial value. Note that this attribute *will not exist* if the kernel doesn’t support changing the direction of a GPIO, or it was exported by kernel code that didn’t explicitly allow userspace to reconfigure this GPIO’s direction.

value” 【數位 0 與 1 之值】… reads as either 0 (low) or 1 (high). If the GPIO is configured as an output, this value may be written;
any nonzero value is treated as high.

If the pin can be configured as interrupt-generating interrupt
and if it has been configured to generate interrupts (see the description of “edge”), you can poll(2) on that file and poll(2) will return whenever the interrupt was triggered. If you use poll(2), set the events POLLPRI and POLLERR. If you use select(2), set the file descriptor in exceptfds. After poll(2) returns, either lseek(2) to the beginning of the sysfs file and read the new value or close the file and re-open it to read the value.

edge” 【上升或下降邊緣】… reads as either “none“, “rising“, “falling“, or “both“. Write these strings to select the signal edge(s)
that will make poll(2) on the “value” file return. This file exists only if the pin can be configured as an interrupt generating input pin.

active_low” 【負邏輯】… reads as either 0 (false) or 1 (true). Write
any nonzero value to invert the value attribute both for reading and writing. Existing and subsequent poll(2) support configuration via the edge attribute for “rising” and “falling” edges will follow this setting.

GPIO controllers have paths like /sys/class/gpio/gpiochip42/ (for the controller implementing GPIOs starting at #42) and have the following read-only attributes唯讀屬性】:

/sys/class/gpio/gpiochipN/

base” 【接腳基底】… same as N, the first GPIO managed by this chip

label“【晶片標籤】 … provided for diagnostics (not always unique)

ngpio” 【 GPIO 個數】… how many GPIOs this manges (N to N + ngpio – 1) Board documentation should in most cases cover what GPIOs are used for what purposes. However, those numbers are not always stable; GPIOs on a daughtercard might be different depending on the base board being used, or other cards in the stack. In such cases, you may need to use the gpiochip nodes (possibly in conjunction with schematics) to determine the correct GPIO number to use for a given signal.

Exporting from Kernel code
————————–
Kernel code can explicitly manage exports of GPIOs which have already been requested using gpio_request():

/* export the GPIO to userspace */
int gpiod_export(struct gpio_desc *desc, bool direction_may_change);

/* reverse gpio_export() */
void gpiod_unexport(struct gpio_desc *desc);

/* create a sysfs link to an exported GPIO node */
int gpiod_export_link(struct device *dev, const char *name,
struct gpio_desc *desc);

/* change the polarity of a GPIO node in sysfs */
int gpiod_sysfs_set_active_low(struct gpio_desc *desc, int value);

After a kernel driver requests a GPIO, it may only be made available in the sysfs interface by gpiod_export(). The driver can control whether the signal direction may change. This helps drivers prevent userspace code from accidentally clobbering important system state.

This explicit exporting can help with debugging (by making some kinds of experiments easier), or can provide an always-there interface that’s suitable for documenting as part of a board support package.

After the GPIO has been exported, gpiod_export_link() allows creating symlinks from elsewhere in sysfs to the GPIO sysfs node. Drivers can use this to provide the interface under their own device in sysfs with a descriptive name.

Drivers can use gpiod_sysfs_set_active_low() to hide GPIO line polarity differences between boards from user space. Polarity change can be done both before and after gpiod_export(), and previously enabled poll(2) support for either rising or falling edge will be reconfigured to follow this setting.

 

讓我們在此舉個簡單的例子,如何控制『樹莓派 B+』上的『電源 LED 』 PWR LED ── BCM-GPIO35 ──的呢?

pi@raspberrypi ~ $ sudo -s

root@raspberrypi:/home/pi# cd /sys/class/gpio/
root@raspberrypi:/sys/class/gpio# ls
export	gpiochip0  gpiochip250	unexport

# 控制 B+ PWR LED
root@raspberrypi:/sys/class/gpio# echo "35" > export 
root@raspberrypi:/sys/class/gpio# ls
export	gpio35	gpiochip0  gpiochip250	unexport

# 進入 export 的 gpio35 子目錄
root@raspberrypi:/sys/class/gpio# cd gpio35
root@raspberrypi:/sys/class/gpio/gpio35# ls
active_low  direction  edge  power  subsystem  uevent  value

# 設定為輸出 out
root@raspberrypi:/sys/class/gpio/gpio35# echo "out" > direction 

# PWR LED On
root@raspberrypi:/sys/class/gpio/gpio35# echo "1" > value 
# PWR LED Off
root@raspberrypi:/sys/class/gpio/gpio35# echo "0" > value 

# 離開  gpio35 子目錄,準備 unexport
root@raspberrypi:/sys/class/gpio/gpio35# cd ..
root@raspberrypi:/sys/class/gpio# echo "35" > unexport 
root@raspberrypi:/sys/class/gpio# ls
export	gpiochip0  gpiochip250	unexport
root@raspberrypi:/sys/class/gpio# exit
pi@raspberrypi ~ $

 

假使你知道『樹莓派 B+』上的『 ACT LED 』── SD 卡讀/寫燈號 ── 是用【 BCM-GPIO47 】.使用同樣的方式可以控制它嗎??

 

 

 

Physical computing ︰《三》 GPIO 溯源《上》

自《史記‧孔子世家》開始,因為孔子後裔的封爵、世襲與祭祀等等傳承,孔子家譜的修訂一直是當代的朝廷來慎重完成,但只及於嫡長者一脈。元豐甲子年間,孔子之第四十六代孫『孔宗翰』,當時官居朝議大夫,創修『孔氏家譜』,始為刊印。一九三七年民國版的《孔子世家譜》共有四集,收錄孔子後裔五十六餘萬人。據聞《孔子世家譜》是唯一在中國歷史上,被保存最完整的家譜,也是全世界歷史裡極古久的家譜,同時為《金氏世界紀錄》認可是全世界歷史最悠遠的族譜。

事物』雖說總有『來源』,『理念』雖講其來『有自』,然而並不是都有『紀錄』和『整理』,以至於常常難以在時流中『溯源』的了。隨著 Linux 系統的發展與茁壯,很早就有像『 uClinux 』此種專案將之移植到『嵌入式系統』 Embedded system 上。現今 Linux 在 SoC系統單晶片』  System on Chip 的應用上更是方興未艾。

一般 SoC 的製造者為著便利使用者能夠開發的多種多樣『應用』與『整合』,通常會有為數不少的『 GPIO 』接腳 ── 通用可變化功能性與輸出入 ──,為什麼呢?因為應用上的『需求規格』才能決定多少種『輸入』,至少幾個『輸出』,需要怎樣的週邊裝置『擴充性』等等。然而 Linux kernel 建基於 PC x86,這一個『架構平台』 platform 曾經一直是由『 Intel 』與『 Microsoft 』所主導,因而『 GPIO 』的軟體設計也就依此『架構平台』而定的了!更因著商業『競爭』和『保護』,許多『系統單晶片』的 Linux 『中介軟體』 Middleware 的提供者,各自『修補』 patch 『核心』 kernel ,於是『 GPIO 』的『軟體架構』問題日益嚴重。

二零零六年,在

LKML.ORG? 】︰

In case you haven’t read the titlebar of your webbrowser’s window: this site is the (unofficial) Linux Kernel Mailing List archive. This mailing list is a rather high-volume list, where (technical) discussions on the design of, and bugs in the Linux kernel take place. If that scares you, please read the FAQ.

David Brownell 的一封《電郵》【 Re: [-mm patch 1/4] GPIO framework for AVR32 】開啟了『 GPIO 』之『軟體架構』的討論,大體可說到二零零八年【※Re: [ patch 2.6.24-rc6-mm 2/9] gpiolib: add gpio provider infrastructure 】之前, Linux kernel 的
GPIO Sysfs Interface for Userspace 》整體已經完成。讀者可以參考《  GPIO Interfaces 》與《 Linux/include/linux/gpio.h 》文件作進一步了解。

舉例來說,在『樹莓派』上可以用︰

# GPIO 晶片提供者
cd /sys/class/gpio/gpiochip0

ls
base  label  ngpio  power  subsystem  uevent

# 標籤
cat label 
bcm2708_gpio

# GPIO 個數
cat ngpio 
54

# 第一個 GPIO 編號
cat base 
0

知道竟有五十四個『 GPIO 』!!

在此根據《 RPi Low-level peripherals 》上的整理,摘要如下︰

GPIO 電壓準位】是 3.3V = 3V3,不是 5V,沒有『過高電壓』 over-voltage 保護電路,務必小心。尤其『注意』『 P1 接頭』上的『 5V 』── Pin 2 與 Pin 4 ── 千萬別和『任一接腳』發生接觸『短路』,否則??恐燒掉了!!

GPIO hardware hackingGPIO 硬體劈砍

Raspberry-Pi-GPIO-Layout-Revision-1
Rev 1.0

BCM-GPIO 0, 1, 4, 7, 8, 9, 10, 11, 14, 15, 17, 18, 21, 22, 23, 24, 25

Raspberry-Pi-GPIO-Layout-Revision-2
Rev 2.0

BCM-GPIO 2, 3, 4, 7, 8, 9, 10, 11, 14, 15, 17, 18, 22, 23, 24, 25, 27

Raspberry-Pi-GPIO-Layout-Model-B-Plus-rotated-2700x900-1024x341
A+/B+

前二十六根接腳定義和 Rev 2.0 相同