0

I am trying to write a basic Linux GPIO user space application. For some reason, I am able to open the export file and export the GPIO with the given number. However, after exporting it, I cannot specify whether it is input or output because the /sys/class/gpio/gpio<###>/direction file is not created. As a result, my C errs out.

Here is the code

#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;
}

Output from run:

root@plnx_arm:~# /usr/bin/basic-gpio

GPIO test running...

GPIO exported successfully

Cannot open GPIO direction it

File is there

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

active_low device direction edge power subsystem uevent value

John Frye
  • 255
  • 6
  • 22
  • The file is obviously there when you run `ls /sys/class/gpio/gpio971/`. It is possible there is a delay between writing the gpio number to the `export` file and the corresponding `gpio971` directory showing up. What happens if you insert a short delay after exporting the pin? – larsks Nov 01 '17 at 15:52
  • Also, it's a good idea to use the `perror` function to display the reason that a system call failed (see [here](https://stackoverflow.com/questions/12102332/when-should-i-use-perror-and-fprintfstderr) for some discussion on that topic). – larsks Nov 01 '17 at 15:55

1 Answers1

1

You need to open file "/sys/class/gpio/gpio971/direction" and not "/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);
    }

You can refer [1], and get the code to export/unexport/set direction/read/write gpio pin.

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

Prabhakar Lad
  • 1,248
  • 1
  • 8
  • 12