The Linux Kernel offers the GPIOLIB interface to access the GPIO pins from the User Space. To enable the GPIOLIB interface make sure you compile your kernel with the following options.
CONFIG_ARCH_REQUIRE_GPIOLIBNow, you can able to access and manipulate the GPIO's from the User Space using the standard C calls such as Open, Write, Read, Close etc.
CONFIG_GPIOLIB
CONFIG_GPIO_SYSFS
Before manipulating the GPIO the specific GPIO pins has to be exported and configured appropriately. Each GPIO on the Processor will have a unique number, please refer to the processor manual.
To export an GPIO you need to open the export interface of the GPIOLIB and write the GPIO number you want to export.
int exportfd;
exportfd = open("/sys/class/gpio/export", O_WRONLY);
if (exportfd < 0)
{
printf("Cannot open GPIO to export it %d\n", errno);
return -1;
}
Write the GPIO you want to export and close the export interface.
write(exportfd, "149", 4);
close(exportfd)
Next, You will need to configure the direction of the GPIO using the direction interface of GPIOLIB.
int directionfd;
directionfd = open("/sys/class/gpio/gpio149/direction", O_RDWR);
if (directionfd < 0)
{
printf("Cannot open GPIO direction for 149\n");
return -1;
}
Write "in" if the GPIO is input or "out" if the GPIO is output and close the interface.
write(directionfd, "out", 4);
close(directionfd)
You can now use the value interface of GPIOLIB to set/clear the GPIO pin.
To make the GPIO line High
int valuefd;
valuefd = open("/sys/class/gpio/gpio149/value", O_RDWR);
if (valuefd < 0)
{
printf("Cannot open GPIO value for 149\n");
return -1;
}
write(valuefd, "1", 2);
close(valuefd);
To make the GPIO line Low
int valuefd;
valuefd = open("/sys/class/gpio/gpio149/value", O_RDWR);
if (valuefd < 0)
{
printf("Cannot open GPIO value for 149\n");
return -1;
}
write(valuefd, "0", 2);
close(valuefd);
You can use the read() function to read the state of the GPIO.
In the next post we will see how to pass the interrupts from Kernel Space to User Space.
3 Responses to "Linux - Accessing GPIO from User Space"
Hello there.
Do you know how to do it on Android it seems you do not have access tu user space, except for a folder where your app resides.
You need to be a super user. You can try to run the program from adb shell. I am not sure about accessing it from an android application.
Hi,
where is a reference for the second post??
("In the next post we will see how to pass the interrupts from Kernel Space to User Space.")
Post a Comment