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

Products related

H10

Features Index Buy

Single Board Computer based on RoadRunner Linux SOM (Included)
  • Low power consumption
  • Two USB Host 2.0 ports (one configurable as USB client on the USB-C connector)
  • One 10/100 Mbit/s Lan port
  • 2 Acme Sensor ports
  • Huge set of GPIOS, SPI, I2C and serial lines

Features Index Buy

Battery-free energy harvesting solar powered LoRa sensor
  • Low power consumption:
    Stand-by mode 4.29 µW
    Transmit mode 66 mW
  • Energy harvesting from in-door ambient light (Just 50 lux)
  • Energy storage based on hybrid supercap
  • Open source RIOT OS
  • Ready for LoRa and LoRaWan
H10

Features Buy

A collection of sensors ready to be connected to the FOX Board D27 and Berta-H10 fast prototiping board.
  • High-accuracy
  • Small footprint
  • High reliability
  • Low-power
  • Cost effective
  • Pluggable by FPC cable