【发布时间】:2018-04-13 22:53:54
【问题描述】:
我正在尝试编写一个基本的 Linux GPIO 用户空间应用程序。出于某种原因,我能够打开导出文件并导出具有给定编号的 GPIO。但是,导出它后,我无法指定它是输入还是输出,因为 /sys/class/gpio/gpio/direction 文件没有创建。结果,我的 C 出错了。
这里是代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
int valuefd, exportfd, directionfd;
printf("GPIO test running...\n");
exportfd = open("/sys/class/gpio/export", O_WRONLY);
if(exportfd < 0)
{
printf("Cannot open GPIO to export it\n");
exit(1);
}
write(exportfd, "971", 4);
close(exportfd);
printf("GPIO exported successfully\n");
directionfd = open("/sys/class/gpio971/direction", O_RDWR);
if(directionfd < 0)
{
printf("Cannot open GPIO direction it\n");
exit(1);
}
write(directionfd, "out", 4);
close(directionfd);
printf("GPIO direction set as output successfully\n");
valuefd = open("/sys/class/gpio/gpio971/value", O_RDWR);
if(valuefd < 0)
{
printf("Cannot open GPIO value\n");
exit(1);
}
printf("GPIO value opened, now toggling...\n");
while(1)
{
write(valuefd, "1", 2);
write(valuefd, "0", 2);
}
return 0;
}
运行输出:
root@plnx_arm:~# /usr/bin/basic-gpio
GPIO 测试正在运行...
GPIO 导出成功
无法打开GPIO方向它
文件在那里
root@plnx_arm:~# ls /sys/class/gpio/gpio971/
active_low 设备方向边缘电源子系统 uevent值
【问题讨论】:
-
当你运行
ls /sys/class/gpio/gpio971/时,文件显然就在那里。将 gpio 编号写入export文件和显示相应的gpio971目录之间可能存在延迟。如果您在导出 pin 后插入一小段延迟会发生什么? -
另外,使用
perror函数来显示系统调用失败的原因是个好主意(有关该主题的一些讨论,请参阅here)。