Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux gpio c api

Tags:

linux

gpio

I have an powerpc board with 3.2 kernel running on it. Accessing gpio with sysfs works as expected e.g.

> echo 242 > /sys/class/gpio/export
> cat /sys/class/gpio/gpio242/value
>  1

Is there no API to direct access gpio pins from user space? Must I deal with the text based sysfs interface?

I seach for something like: gpio_set(int no, int val);

Thanks Klaus

like image 643
Klaus Avatar asked Nov 03 '22 22:11

Klaus


2 Answers

Edit: sysfs direct access for GPIOs is deprecated, new way is programmatic through libgpiod

sysfs is the lowest level at which you will be able to manipulate GPIO in recent kernels. It can be a bit tedious but it offers several advantages over the old style API:

  • No ugly ioctl
  • Can be scripted very easily (think startup scripts)
  • For inputs, the "value" file can easily be poll-ed for rising/falling/both edges and it will be very reactive to hardware interrupts

I have no example code at the moment but when accessing them through C code, I often implemented a very simple wrapper manipulating file descriptors and having variations of the following interface:

int gpio_open(int number, int out); /* returns handle (fd) */
int gpio_close(int gpio);
int gpio_set(int gpio, int up);
int gpio_get(int gpio, int *up);
int gpio_poll(int gpio, int rising_edge, int timeout);

From then, the implementation is pretty straightforward.

like image 174
Léo Germond Avatar answered Nov 07 '22 21:11

Léo Germond


Once you have the devices created in the vfs tree, you can open them like typical files assuming you have a driver written and have the correct major and minor numbers assigned in the makedev file that creates the gpio pins on the vfs tree.

like image 41
San Jacinto Avatar answered Nov 07 '22 21:11

San Jacinto