###### tags: `RaspberryPi` libgpiod === Linux過去常利用讀寫sysfs,達成操作GPIO的目的[sysfs參考](https://www.kernel.org/doc/Documentation/gpio/sysfs.txt)。 目前提供採用新的[libgpiod](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/about/),提供更進階(event polling, setting/reading multiple values)高速的(需要證實)操作GPIO方式。除此之外,libgpiod提供了C和python的API,可供使用。由於libgpiod算是核心(Linux Kernel)比較新的操作GPIO方式,在一些系統上需要透過安裝,完成環境的建置。 libgpiod提供了以下簡易的API,操作GPIO[參考](https://www.beyondlogic.org/an-introduction-to-chardev-gpio-and-libgpiod-on-the-raspberry-pi/): - gpiodetect: gpiochips的清單。 ``` $ sudo gpiodetect gpiochip0 [pinctrl-bcm2835] (54 lines) gpiochip1 [raspberrypi-exp-gpio] (8 lines) ``` - gpioinfo: 列出所有gpiochips所包含line(gpio)資料。 ![](https://i.imgur.com/ptJko5t.png) - gpioget: 讀取GPIO的值 - gpioset: 設定GPIO的值 ``` Usage: gpioset [OPTIONS] <chip name/number> <offset1>=<value1> <offset2>=<value2> ... Set GPIO line values of a GPIO chip and maintain the state until the process exits Options: -h, --help: display this message and exit -v, --version: display the version and exit -l, --active-low: set the line active state to low -m, --mode=[exit|wait|time|signal] (defaults to 'exit'): tell the program what to do after setting values -s, --sec=SEC: specify the number of seconds to wait (only valid for --mode=time) -u, --usec=USEC: specify the number of microseconds to wait (only valid for --mode=time) -b, --background: after setting values: detach from the controlling terminal Modes: exit: set values and exit immediately wait: set values and wait for user to press ENTER time: set values and sleep for a specified amount of time signal: set values and wait for SIGINT or SIGTERM Note: the state of a GPIO line controlled over the character device reverts to default when the last process referencing the file descriptor representing the device file exits. This means that it's wrong to run gpioset, have it exit and expect the line to continue being driven high or low. It may happen if given pin is floating but it must be interpreted as undefined behavior. ``` - gpiofind: 列出指定gpiochips名稱的GPIO資訊 - gpiomon: 等待GPIO事件(觸發) 下列命令可讓GPIO26輸出hi 1秒 ``` gpioset --mode=time --sec=1 pinctrl-bcm2835 26=1 ``` --- 接著開始講解原理了: 由於GPIO控制位於kernel space,因此位於user space的開發者,則必須借助一些方式與kernel space通訊,達到操作GPIO的目的。 sysfs或character device interface可以與kernel space的gpiolib通訊達成控制GPIO的目的。libgpio提供了一些API,協助操作character device interface。藉由libgpiod,讓開發者可以很輕易的操作character device interface。 ![](https://i.imgur.com/AeiSlSN.png) ![](https://i.imgur.com/0SJjXOj.png) ![](https://i.imgur.com/LQ52CLB.png) --- C API: --- Python API: ```Clike= gpiod_line* gpiod_chip_get_line ( gpiod_chip* chip uint offset ) ```