Using libgpiod

The libgpiod library is a straigthforward C API that encapsulates the interaction with Linux’s GPIO.

To get started with the library, you can find several excellent resources online. GPIO Programming: Exploring the libgpiod Library can show you a good introduction. For the full documentation, you can check your system’s help or kernel.org’s gpiod.h source.

Installation

The library is available through the system’s repositories in any modern Linux distribution. In apt-based systems, install it by running:

ubuntu@rpi:~$ sudo apt update
ubuntu@rpi:~$ sudo apt install libgpiod-dev libgpiod-doc

Example 2: Using inputs

The following code reads the value of the first input at a rate of 10 times per second, and sets the first output to the read value every time.

// Output_1 io1212 = Input_1 io1212
int count = 600;
while (count) {
  int val = gpiod_line_get_value(input_lines[Input_1]);
  if (val < 0) {
      perror("Read line input failed");
      return 1;
  }
  int ret = gpiod_line_set_value(output_lines[Output_1], val);
  if (ret < 0) {
      perror("Set line output failed");
      return 1;
  }
  usleep(100000);
  count--;
}

You can test it by replacing the “blink” logic in the previous example.