Difference between revisions of "Manage the GPIO lines in C with libgpiod"

From KoanSoftware Wiki
Jump to: navigation, search
(Created page with "== Manage the GPIO lines in C with libgpiod == Since linux 4.8 the GPIO sysfs interface is deprecated. User space should use the character device instead. '''libgpiod''' en...")
 
(No difference)

Latest revision as of 09:07, 12 September 2024

Manage the GPIO lines in C with libgpiod

Since linux 4.8 the GPIO sysfs interface is deprecated. User space should use the character device instead.

libgpiod encapsulates the ioctl calls and data structures behind a straightforward API.


Manage the GPIO using the C language

- libgpiod documentation

- libgpiod-example git repo


Example

 #include <gpiod.h>
 #include <stdio.h>
 #include <unistd.h>
 
 #ifndef	CONSUMER
 #define	CONSUMER	"Consumer"
 #endif
 
 int main(int argc, char **argv)
 {
   char *chipname = "gpiochip0";
   unsigned int line_num = 23;	// GPIO Pin #23
   unsigned int val;
   struct gpiod_chip *chip;
   struct gpiod_line *line;
   int i, ret;
 
   chip = gpiod_chip_open_by_name(chipname);
   if (!chip) {
     perror("Open chip failed\n");
     goto end;
   }
 
   line = gpiod_chip_get_line(chip, line_num);
   if (!line) {
     perror("Get line failed\n");
     goto close_chip;
   }
 
   ret = gpiod_line_request_output(line, CONSUMER, 0);
   if (ret < 0) {
     perror("Request line as output failed\n");
     goto release_line;
   }
 
   /* Blink 20 times */
   val = 0;
   for (i = 20; i > 0; i--) {
     ret = gpiod_line_set_value(line, val);
     if (ret < 0) {
       perror("Set line output failed\n");
       goto release_line;
     }
     printf("Output %u on line #%u\n", val, line_num);
     sleep(1);
     val = !val;
   }
 
 release_line:
   gpiod_line_release(line);
 close_chip:
   gpiod_chip_close(chip);
 end:
   return 0;
 }