Linux 导出时未创建 GPIO 值文件

Linux GPIO Value File Not Created on Export

我正在尝试编写一个基本的 Linux GPIO 用户 space 应用程序。出于某种原因,我能够打开导出文件并导出具有给定编号的 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 test running...

GPIO exported successfully

Cannot open GPIO direction it

文件在那里

root@plnx_arm:~# ls /sys/class/gpio/gpio971/

active_low device direction edge power subsystem uevent value

您需要打开文件“/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],获取代码到export/unexport/set direction/read/write gpio pin。

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