【问题标题】:Linux GPIO Value File Not Created on Export导出时未创建 Linux GPIO 值文件
【发布时间】: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)。

标签: c linux gpio


【解决方案1】:

您需要打开文件“/sys/class/gpio/gpio971/direction”而不是“/sys/class/gpio971/direction”

   directionfd = open("/sys/class/gpio/gpio971/direction", O_RDWR);

    if(directionfd < 0)
    {
        printf("Cannot open GPIO direction it\n");
        exit(1);
    }

您可以参考[1],获取导出/取消导出/设置方向/读/写gpio pin的代码。

[1]https://elinux.org/RPi_GPIO_Code_Samples#sysfs

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2021-10-14
    相关资源
    最近更新 更多