Manage the 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.

Manage the GPIO using Python 3 language

On Debian distribution install the Python3 libgpiod libraries by typing:

sudo apt update
sudo apt install python3-libgpiod

Output example - A blinking led

# GPIO used PA17

import gpiod
import time

chip=gpiod.Chip('gpiochip0')
line = gpiod.find_line("PA17")
lines = chip.get_lines([line.offset()])
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 ?

With this loop is possible to generate a 42kHz square signal on a GPIO line using a Roadrunner SOM @ 500mHz

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

Input example - Reading a GPIO line

# GPIO used PD30

import gpiod
import time

chip = gpiod.Chip('gpiochip0')
line = gpiod.find_line("PD30")
lines = chip.get_lines([line.offset()])
lines.request(consumer='foobar', type=gpiod.LINE_REQ_DIR_IN)

while True:
    print(lines.get_values())
    time.sleep(1)
    print(lines.get_values())
    time.sleep(1)

Where to find the Python3 gpiod API documentation

Lauch the python3 interpreter

python3

then type:

>>> import gpiod
>>> help(gpiod)

Manage the GPIO using the C language

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 ?

With this loop is possible to generate a 300kHz square signal on a GPIO line using a Roadrunner SOM @ 500mHz

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

Links

Sergio Tanzilli
Systems designer, webmaster of www.acmesystems.it and founder of Acme Systems srl

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