Reputation: 255
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
Upvotes: 0
Views: 1297
Reputation: 1438
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
Upvotes: 1