Skip to content

Raspberry Pi GPIO using gpiod

gpiod (libgpiod) is a modern, fast, and safe way to control GPIOs on Linux-based systems the gpiod library work with /dev/gpiochip*

Note

gpiod replaces the deprecated /sys/class/gpio interface.

Install

sudo apt install gpiod

usage

gpiod installed 6 utils

  • gpiodetect: List all GPIO chips on the system
  • gpiofind: Find a GPIO by label
  • gpioget: Turn GPIOs ON/OFF
  • gpioset: Read digital input state
  • gpioinfo: Show info about all lines on a chip
  • gpiomon: Monitor GPIOs for edge events

Demo: using gpiod utilities with rpi5

alt text

gpiodetect
1
2
3
4
5
6
7
gpiodetect
#
gpiochip0 [gpio-brcmstb@107d508500] (32 lines)
gpiochip1 [gpio-brcmstb@107d508520] (4 lines)
gpiochip2 [gpio-brcmstb@107d517c00] (15 lines)
gpiochip3 [gpio-brcmstb@107d517c20] (6 lines)
gpiochip4 [pinctrl-rp1] (54 lines)

Note

Control the j8 header

gpioset
gpioset gpiochip4 17=1
gpioset gpiochip4 17=0

Python and CPP

cpp

install
sudo apt install -y libgpiod-dev 
blink cpp code
#include <gpiod.h>
#include <iostream>
#include <chrono>
#include <thread>

int main() {
    const char* chipname = "gpiochip4";  // Raspberry Pi 5 J8 header GPIOs
    unsigned int line_num = 17;          // GPIO17 (BCM)

    gpiod_chip* chip = gpiod_chip_open_by_name(chipname);
    if (!chip) {
        std::cerr << "Failed to open GPIO chip\n";
        return 1;
    }

    gpiod_line* line = gpiod_chip_get_line(chip, line_num);
    if (!line) {
        std::cerr << "Failed to get line\n";
        gpiod_chip_close(chip);
        return 1;
    }

    if (gpiod_line_request_output(line, "gpio_toggle", 0) < 0) {
        std::cerr << "Failed to request line as output\n";
        gpiod_chip_close(chip);
        return 1;
    }

    for (int i = 0; i < 10; ++i) {
        gpiod_line_set_value(line, 1);
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        gpiod_line_set_value(line, 0);
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }

    gpiod_line_release(line);
    gpiod_chip_close(chip);
    return 0;
}
build
g++ -o gpio_toggle gpio_blink.cpp -lgpiod

python

sudo apt install python3-libgpiod
blink cpp code
import gpiod
import time

CHIP_NAME = "gpiochip4"  # On Raspberry Pi 5
LINE_OFFSET = 17         # BCM GPIO number

# Open the GPIO chip and get the line
chip = gpiod.Chip(CHIP_NAME)
line = chip.get_line(LINE_OFFSET)

# Request the line as output (v2.x API)
line.request(consumer="python-gpiod", type=gpiod.LINE_REQ_DIR_OUT)

# Blink loop
for _ in range(10):
    line.set_value(1)
    time.sleep(0.5)
    line.set_value(0)
    time.sleep(0.5)

line.release()