Using libgpiod to access GPIO - cu-ecen-aeld/yocto-assignments-base GitHub Wiki

Overview

This page describes the use of libgpiod library to access GPIOs on the Raspberry Pi. The library helps map the gpiochip0 char driver (found at /dev/gpiochip0) to the user space application.

The old (and most used) way of interfacing with gpios was using the sysfs interface. However, this method is deprecated since kernel v4.8 and is replaced with the gpiochip0 char device driver. To use this driver, the maintainer of the GPIO kernel framework (Bartosz Golaszewski) released the libgpiod library.

Please refer to the working example at this pull request.

Test Application Implementation Steps

  1. Start by installing the required package on your local machine

sudo apt-get install libgpiod-dev

This will install the required libgpiod development package along with its dependencies.

  1. Use the example code which contains the gpioreadtest and gpiowritetest applications. These are derived from the libgpiod examples provided by the author.
    Use the Makefile to compile these on your local machine first.

  2. Create a recipe for installing this test code to your target machine. An example recipe is shown which is contained in the gpiotest package. Note the use of DEPENDS to build the application.

  3. Modify the build script to add the new gpiotest package in the conf/bblayers.conf and the recipe in the conf/local.conf. You will need to add poky, open-embedded and raspberrypi as submodules to your project before you run the script. (I verified this using the dunfell branch)

  4. Build the image. You should see that the meta-gpiotest package is added. After flashing the image to the SD Card, boot your Raspberry Pi.

  5. Check the /usr/bin directory. The gpioreadtest and gpiowritetest applications should be visible. You can run these and test the output at the respective pins using a logic analyzer or an LED.

GPIO Read on Pin 4 - First measurement is when the pin is floating, second is connecting it to GND

GPIO Write on Pin 4 - 10uS (Note: Example code sets the pin for 1s)

  1. You can now write your own application to interface with the GPIOs based on these example applications. Refer to the libgpiod source to figure out how to use the APIs.

References

  1. libgpiod Presentation by Bartosz
  2. Difference between sysfs and gpiochip0
  3. More implementation and packages required
  4. Further reading from kernel.org documentation