1、采用sysfs的方式控制,这是内核标准的sysfs接口
如:
echo 25 > /sys/class/gpio/export
echo "out" > /sys/class/gpio/gpio25/direction
echo 1 > /sys/class/gpio/gpio25/value
2、采用libgpiod 控制内核生成的节点来控制/dev/gpiochip0或着是通过(yocto生成的可执行应用程序进行控制)
命令控制:
gpiodetect gpiofind gpioget gpioinfo gpiomon gpioset
如控制一个led的亮和灭:
./gpioset 0 44=1 //点亮led
./gpioset 0 44=0 //熄灭led
对应的命令说明:
gpiodetect 列出所有的gpio (如:gpiodetect)
gpioinfo 列出某个gpio控制器的情况(如:gpioinfo 0)
gpioset 设置gpio (如:./gpioset 0 44=1)
gpioget 读取gpio (如:gpioget 0 44)
gpiomon 监控gpio的状态(如:gpiomon 0 44
event: FALLING EDGE offset: 44 timestamp: [1689149426.089597926])
代码控制:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <gpiod.h> //include file
void main(void) {
struct gpiod_chip *chip;
struct gpiod_line *line;
int req, value;
chip = gpiod_chip_open("/dev/gpiochip0");
//or chip = gpiod_chip_open_by_name("gpiochip0");
if (!chip) {
printf("Fail to open gpiochip0!\n");
return ;
}
line = gpiod_chip_get_line(chip, 11);
if (!line) {
printf("Fail to get gpio line!\n");
goto err;
}
req = gpiod_line_request_input(line, "gpio_state");
if (req) {
printf("Fail to config input!\n");
goto err;
}
value = gpiod_line_get_value(line);
printf("GPIO value is: %d\n", value);
if(gpiod_line_is_requested(line)) {
printf("release gpio request!,and go on\n");
gpiod_line_release(line);
}
/* config as output and set a description */
req = gpiod_line_request_output(line, "gpio-bline", GPIOD_LINE_ACTIVE_STATE_HIGH);
if (req) {
printf("Fail to config output!\n");
goto err;
}
while (1)
{
/* GPIO Toggle */
value = !value;
gpiod_line_set_value(line, value);
/* print LED status */
if(value)
printf("LED turns ON\n");
else
printf("LED turns OFF\n");
sleep(1);
}
err:
gpiod_chip_close(chip);
return;}
说明:
如下是内核官方从sysfs控制gpio到libgpiod控制gpio的说明:
kernel/git/torvalds/linux.git - Linux kernel source tree