Manage GPIO lines in Python3 and 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.

Python 3

On Debian distribution install the Python3 libgpiod libraries by typing:

sudo apt update
sudo apt install python3-libgpiod

Example - Blinking led

# GPIO used PA17

import gpiod
import time

chip=gpiod.Chip('gpiochip0')

lines = chip.get_lines([17])
lines.request(consumer='foobar', type=gpiod.LINE_REQ_DIR_OUT, default_vals=[0])

while True:
    lines.set_values([1])
    time.sleep(1)
    lines.set_values([0])
    time.sleep(1)

How fast is it

Using this loop it is possible to toggle a GPIO line at about 42kHz on a Roadrunner SOM @ 500mHz

while True:
    lines.set_values([1])
    lines.set_values([0])

C

On Debian distribution install the libgpiod libraries and build essential tools by typing:

sudo apt update
sudo apt install libgpiod-dev build-essential

Install git

sudo apt git

Then clone where you can find some lite examples (https://github.com/starnight/libgpiod-example):

git clone https://github.com/starnight/libgpiod-example

How fast is it

Using this loop it is possible to toggle a GPIO line at about 300kHz on a Roadrunner SOM @ 500mHz

val = 0;
for (i = 10000; i > 0; i--) {
    ret = gpiod_line_set_value(line, val);
    val = !val;
}

Links

Sergio Tanzilli
System designer, webmaster and Acme Systems co-founder

Personal email: tanzilli@acmesystems.it
Webpage: https://www.acmesystems.it
Github repositories: https://github.com/tanzilli and https://github.com/acmesystems
Telegram group dedicated to the Acme Systems boards: https://t.me/acmesystemssrl