1. 架构
2. 有两种操作方法
2.1 第一种: sysfs接口(旧, 已废弃)
2.2 第二种: 字符设备接口(新)
3. 如何使用sysfs接口控制gpio?
3.1 确定要使用的gpio号(怎么知道gpio号呀?)
3.2 将gpio号写入文件/sys/class/gpio/export中
# echo 333 > /sys/class/gpio/export
3.3 将gpio配置为输入还是输出
配置为输出示例如下:
# echo out > /sys/class/gpio/gpio333 direction
3.4 如果3.3设置为输入,那么读取gpio的值
# cat /sys/class/gpio/gpio333/value
3.5 如果3.3设置为输出, 那么向gpio写入值
# echo 1 > /sys/class/gpio/gpio333/value
4. 如何使用字符设备接口控制gpio?
4.1 有两种方法
4.1.1 使用libgpiod编程
4.1.2 使用命令行工具
4.2 使用libgpiod编程
示例如下:
void main() { struct gpiod_chip *chip; struct gpiod_line *line; int req, value; chip = gpiod_chip_open("/dev/gpiochip0"); if (!chip) return -1; line = gpiod_chip_get_line(chip, 3); if (!line) { gpiod_chip_close(chip); return -1; } req = gpiod_line_request_input(line, "gpio_state"); if (req) { gpiod_chip_close(chip); return -1; } value = gpiod_line_get_value(line); printf("GPIO value is: %d ", value); gpiod_chip_close(chip); }
4.3 使用命令行工具
4.3.1 gpiodetect: 列出所有的gpio
# gpiodetect gpiochip0 [209c000.gpio] (32 lines) gpiochip1 [20a0000.gpio] (32 lines) gpiochip2 [20a4000.gpio] (32 lines) gpiochip3 [20a8000.gpio] (32 lines) gpiochip4 [20ac000.gpio] (32 lines) gpiochip5 [20b0000.gpio] (32 lines) gpiochip6 [20b4000.gpio] (32 lines) gpiochip7 [mcp23s08.0] (8 lines)
4.3.2 gpioinfo: 列出某个gpio控制器的情况
# gpioinfo 0 gpiochip0 - 32 lines: line 0: unnamed unused input active-high line 1: unnamed unused input active-high line 2: unnamed unused input active-high line 3: unnamed "scl" output active-high [used open-drain] line 4: unnamed unused input active-high line 5: unnamed unused input active-high line 6: unnamed "sda" output active-high [used open-drain] line 7: unnamed "Push Button" input active-low [used] line 8: unnamed unused input active-high line 9: unnamed "?" output active-high [used] line 10: unnamed unused input active-high line 11: unnamed unused input active-high
4.3.3 gpioset: 设置gpio
设置gpio控制器0的第9个gpio输出0 (注意在4.3.2中这个gpio是设置为输出的)
# gpioset 0 9=0
4.3.4 gpioget: 读取gpio
# gpioget 0 9
4.3.5 gpiomon: 监控gpio的状态
# gpiomon 0 9