Skip to content
systemcoding.dev
Embedded Linux

Control GPIO Lines From Python With the gpiod Bindings

Blink an LED, read a button and wait for edge events from Python 3.12 with the libgpiod 2.1 gpiod module, using request_lines and LineSettings.

6 min read
Summarize in AI
Flat illustration of a single-board computer with its SoC, memory, header and ports, with the Python, Linux and NXP logos.

The command-line tools are good for a bench, but a product needs a program that holds its lines, reacts to events and shuts down cleanly. Python is the quickest way to get one working on a board that has an interpreter, and libgpiod ships official bindings, a module named gpiod, that wrap the character device. This post uses the version 2 bindings that come with libgpiod 2.1, Python 3.12 and Linux 6.12 to blink an LED, read a button and wait for edge events without polling. It also shows the one thing that trips people: the version 2 API is a different design from the version 1 one that older tutorials use. The module is documented in the libgpiod Python bindings reference.

Install and check the module

The bindings are a separate package from the library on most systems. On Debian-based images they are python3-libgpiod, and the pip name is gpiod. Check the version before writing code against it:

Shell
python3 -c "import gpiod; print(gpiod.__version__)"
Text
2.1.3

If this prints a 1.x number or the import fails, the examples below will not run as written. The older API had gpiod.Chip("gpiochip0"), chip.get_line(17) and line.request(...), which are gone from version 2. Many online examples still use them, so the first step on a confusing error is to check the version.

The model: request lines, then use the request

The version 2 flow has three ideas. A request is an object that represents lines you hold. You create one with gpiod.request_lines(path, consumer=..., config={...}), where config maps each line offset to a LineSettings object that says how to configure it, direction, bias, edges and initial values. Then you read, write or wait through the request. When you close it, the lines are released. Use it as a context manager so it is closed even on an exception.

The program requests line 17 of gpiochip0 as an output starting inactive, then toggles it. Value.ACTIVE and Value.INACTIVE are logical values:

python
import time

import gpiod
from gpiod.line import Direction, Value

CHIP = "/dev/gpiochip0"
LED = 17

with gpiod.request_lines(
    CHIP,
    consumer="blink",
    config={
        LED: gpiod.LineSettings(
            direction=Direction.OUTPUT, output_value=Value.INACTIVE
        )
    },
) as request:
    for _ in range(3):
        request.set_value(LED, Value.ACTIVE)
        time.sleep(0.5)
        request.set_value(LED, Value.INACTIVE)
        time.sleep(0.5)
    print("done")
Text
done

The LED flashes three times, then the with block ends and the request is released. The consumer name blink is what gpioinfo shows while the program runs, which helps when you debug a busy line. If another process holds line 17 the request raises OSError with the errno for busy, which you handle or let end the program.

Read a button

A read needs the line requested as an input. Add a bias so an open button gives a defined level. get_value returns a Value, and comparing it to Value.ACTIVE gives a boolean:

python
import gpiod
from gpiod.line import Bias, Direction, Value

CHIP = "/dev/gpiochip0"
BUTTON = 27

with gpiod.request_lines(
    CHIP,
    consumer="button-read",
    config={
        BUTTON: gpiod.LineSettings(
            direction=Direction.INPUT, bias=Bias.PULL_UP
        )
    },
) as request:
    value = request.get_value(BUTTON)
    print("released" if value == Value.ACTIVE else "pressed")
Text
released

With the button wired to ground and the pull-up enabled, the unpressed line is high, which is logical active, so the program prints released. Hold the button while you run it and it prints pressed. If your chip does not support software-controlled bias, the request raises an error such as OSError: [Errno 95] Operation not supported, and the fix is to use an external resistor and drop the bias argument, or to set the pull in the device tree.

Wait for edges instead of polling

Reading in a loop wastes CPU and misses short presses. The kernel can watch the line and queue an event with a timestamp for each edge. Configure edge detection and a debounce period in the settings, then block in wait_edge_events:

python
from datetime import timedelta

import gpiod
from gpiod.line import Bias, Direction, Edge

CHIP = "/dev/gpiochip0"
BUTTON = 27

with gpiod.request_lines(
    CHIP,
    consumer="button-events",
    config={
        BUTTON: gpiod.LineSettings(
            direction=Direction.INPUT,
            bias=Bias.PULL_UP,
            edge_detection=Edge.BOTH,
            debounce_period=timedelta(milliseconds=10),
        )
    },
) as request:
    while request.wait_edge_events(timedelta(seconds=10)):
        for event in request.read_edge_events():
            kind = "pressed" if event.event_type is event.Type.FALLING_EDGE else "released"
            print(f"line {event.line_offset} {kind} at {event.timestamp_ns} ns")
    print("no events for 10 seconds")
Text
line 27 pressed at 1742311822193450211 ns
line 27 released at 1742311822342017745 ns
no events for 10 seconds

Timestamps are nanoseconds from a kernel clock and the values above are examples. wait_edge_events takes a timeout and returns true when events are waiting, false when the time ran out, so the loop ends cleanly after ten quiet seconds. read_edge_events returns a list of event objects, each with its type, the line offset and the timestamp. A falling edge is a press with the pull-up wiring. The 10 ms debounce is done in the kernel or the controller when it supports it, which ignores contact bounce; without it a single press can generate dozens of events.

Read and write several lines together

A request can hold many lines. get_values and set_values take and return sets together, so a group of lines changes in one operation:

python
import gpiod
from gpiod.line import Direction, Value

with gpiod.request_lines(
    "/dev/gpiochip0",
    consumer="bus",
    config={
        (17, 18, 19): gpiod.LineSettings(direction=Direction.OUTPUT)
    },
) as request:
    request.set_values({17: Value.ACTIVE, 18: Value.INACTIVE, 19: Value.ACTIVE})
    print(request.get_values())
Text
[<Value.ACTIVE: 1>, <Value.INACTIVE: 0>, <Value.ACTIVE: 1>]

The tuple key assigns the same settings to all three offsets, and get_values returns values in the order the offsets were requested. The exact repr of the enum values depends on the version, but the order does not.

Finding lines by name

Offsets change between boards; names from the device tree do not. gpiod.find_line was in version 1. In version 2 you iterate the chip's line info to resolve a name once at startup:

python
import gpiod

with gpiod.Chip("/dev/gpiochip0") as chip:
    offset = chip.line_offset_from_id("status-led")
    print(offset)
Text
21

line_offset_from_id raises OSError if the name does not exist on that chip. Keep the lookup outside any loop.

Mistakes to avoid

Forgetting to close the request holds the lines until the process exits, which in a long-running service means other programs cannot use them, so prefer with. Using values as plain integers works only through the Value enum in version 2, so request.set_value(17, 1) raises a type error; use Value.ACTIVE. And do not mix the old and new APIs in one project, because the old package name and the new one install the same module name.

When Python is the wrong choice

A real-time loop that must toggle a line at a precise frequency does not belong in Python on Linux, where scheduling jitter is milliseconds. Use a hardware timer, a PWM channel or a PRU for that, and use GPIO from user space for slow control signals and events.

Running it as a service

A program like this belongs in a systemd unit that runs as an unprivileged user in the gpio group. Give the unit Restart=on-failure so a transient error does not leave the lines unowned, and add DeviceAllow=/dev/gpiochip0 rw with PrivateDevices=no if you sandbox it. Handle SIGTERM by leaving the event loop and letting the with block close the request, which returns the lines to their default state, and set the consumer name to the unit name so gpioinfo tells you who holds each line.

Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and GNU logos.
Kernels

Write a Pin Controller Driver With pinctrl

Write a Linux 6.12 pin controller driver: pinctrl_desc, pins, groups and functions, the set_mux callback, and the device tree states that consumers select.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.