导出时未创建Linux GPIO值文件

时间:2017-11-01 15:10:34

标签: c linux gpio

我正在尝试编写一个基本的Linux GPIO用户空间应用程序。出于某种原因,我可以打开导出文件并使用给定的数字导出GPIO。但是,导出后,我无法指定它是输入还是输出,因为未创建/ sys / class / gpio / gpio< ###> / direction文件。结果,我犯了错误。

这是代码

#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值

1 个答案:

答案 0 :(得分:1)

你需要打开文件&#34; / sys / class / gpio / gpio971 / direction&#34;而不是&#34; / sys / class / gpio971 / direction&#34;

void SPITransmit(uint8_t data)
{
    SPDR = data;
   while(!(SPSR & (1<<SPIF)));
 }

您可以参考[1],并获取导出/取消端口/设置方向/读取/写入gpio引脚的代码。

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