
Recall first from Timeouts and clock jumps
- SO_RCVTIMEO, poll/select/epoll timeouts and a CLOCK_MONOTONIC timerfd all measure their waits with the kernel's monotonic time, so a wall-clock change does not stretch or shorten them.
- alarm() and setitimer() give one real-time timer per process, race with the blocking call, and are limited by async-signal-safety.
- CLOCK_REALTIME can step with NTP or a manual date change; CLOCK_MONOTONIC cannot, and a DST transition changes only local-time formatting, never the UTC or monotonic clock.
From a pin to a character device
3 min readUntil now every lesson ran on a screen with no outside hardware. This lesson steps onto the Raspberry Pi and its first real interface, GPIO, through the libgpiod char device.
General-purpose input/output: a pin the chip exposes for software to configure as a digital input or output. pins have no fixed role until software gives them one. A pin is a wire the processor can force to one of two voltage levels, or sense on. On the Raspberry Pi the 40-pin header exposes such pins at 3.3 V logic: one level is low (near 0 V) and the other is high (near 3.3 V). Software treats these as digital 0 and 1, and the pin never provides 5 V or more.
A pin's direction decides what it does. An output pin drives the wire: the processor actively pushes it high or low, strong enough to light an LED through a current-limiting resistor. An input pin only samples the wire: it reports the level that an external device (a button, a sensor) places there. Software must configure the direction before use; a pin cannot sensibly do both at once.
Two further properties matter when a level carries a meaning. Active high is the common mapping: logical 1 is the physical high level. Some signals are A line whose logical 1 is represented by the physical low level, common for reset and chip-select signals.: they assert their "on" condition by pulling the wire low. libgpiod lets you declare a line active low so your program writes and reads logical values while the library translates to physical levels.
An input with nothing driving it floats: it reads unpredictably because it is not tied to either rail. A A resistor that weakly connects an input to the high rail so it reads high when nothing else drives it. holds the wire at a default high, and a pull-down resistor holds it at a default low. These internal resistors are essential for buttons, where the switch connects the pin to ground only while pressed and the pull-up supplies a stable high the rest of the time.
Linux exposes GPIO through two interfaces. The old one is sysfs, under /sys/class/gpio: you write a pin number to its export file, then read and write direction and value files. That interface is deprecated since Linux 4.8, but it was not removed: kernels can still build it with CONFIG_GPIO_SYSFS. It is deprecated because it could not request a line atomically. Export, direction and value were separate steps with races between them, there was no record of which process owned a line, and event handling was awkward. The replacement is the character device /dev/gpiochipN, where one request takes a line together with its direction, flags and a consumer name, and the kernel tracks the state per line. libgpiod 1.6 talks to this character device. The kernel's character-device ABI v2 (linux/gpio.h, the GPIO_V2_* ioctls) has existed since 5.10; libgpiod 2.x is a different upstream API and is not what Ubuntu 24.04 or Raspberry Pi OS Bookworm install.
Find your chip before writing code. gpiodetect lists every GPIO chip with its label and line count; gpioinfo prints each line's offset, name and current consumer. On a Raspberry Pi the chip number differs by model and kernel, so read it from gpiodetect instead of hard-coding it. On 40-pin boards, header pin 11 is BCM GPIO17, the line offset used in the examples below.
Requesting and driving a line
2 min readDriving a pin is a four-step sequence: open the chip, obtain the line, request it as an output, then set values. Every call's return value is checked, because any step can fail: the path may not exist, the line may already be requested by someone else, or the request may be refused.
gpiod_chip_open(path) opens the character device such as /dev/gpiochip0 and returns a struct gpiod_chip *, or NULL on error. (Variants open by name, number or label: gpiod_chip_open_by_name and gpiod_chip_open_by_number exist for scripts that cannot guess a path.) gpiod_chip_get_line(chip, offset) returns the struct gpiod_line * for one line number inside that chip, or NULL. gpiod_line_request_output(line, consumer, default_val) reserves the line as an output and drives its initial value; consumer is a short name shown later by gpioinfo so you can tell who holds a line. gpiod_line_set_value(line, value) writes a logical 0 or 1 and returns 0 on success, -1 on error with errno set. gpiod_line_release(line) returns the line and gpiod_chip_close(chip) closes the chip.
Here is a complete program that blinks an LED once per second:
#include <gpiod.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (argc != 3) {
fprintf(stderr, "usage: %s CHIP OFFSET\n", argv[0]);
return EXIT_FAILURE;
}
unsigned int offset = (unsigned int)atoi(argv[2]);
struct gpiod_chip *chip = gpiod_chip_open(argv[1]);
if (!chip) {
perror("gpiod_chip_open");
return EXIT_FAILURE;
}
struct gpiod_line *line = gpiod_chip_get_line(chip, offset);
if (!line) {
perror("gpiod_chip_get_line");
gpiod_chip_close(chip);
return EXIT_FAILURE;
}
if (gpiod_line_request_output(line, "m2s11a-blink", 0) < 0) {
perror("gpiod_line_request_output");
gpiod_chip_close(chip);
return EXIT_FAILURE;
}
for (int i = 0; i < 10; i++) {
if (gpiod_line_set_value(line, i % 2) < 0) {
perror("gpiod_line_set_value");
break;
}
sleep(1);
}
gpiod_line_release(line);
gpiod_chip_close(chip);
return EXIT_SUCCESS;
}
Compile and link it on the target:
gcc -Wall -Wextra -std=c17 -o blink blink.c -lgpiod
Run it with the chip path and the line offset you found in gpioinfo, for example ./blink /dev/gpiochip0 17 on a Raspberry Pi driving header pin 11. The chip number is the only part that varies by board; read it rather than assuming 0.
The character device keeps the line driven only while a process holds the request. When the last process that has the device file descriptor exits, the line reverts to its default state. That is why blink sleeps inside the loop and releases at the end, and why a one-shot tool that sets a value and exits cannot be relied on to leave the pin driven: the level it left behind is undefined behavior unless something else holds the line open. A daemon that must keep a pin asserted therefore holds the request for its whole lifetime.
Reading a line, bias and active state
2 min readFor a plain input, gpiod_line_request_input(line, consumer) reserves the line for reading, and gpiod_line_get_value(line) samples it, returning the logical 0 or 1, or -1 on error. But a bare input floats when nothing drives it, so a button or sensor usually needs a pull-up or pull-down. The plain input and output helpers do not take flags; gpiod_line_request_input_flags, gpiod_line_request_output_flags and the general gpiod_line_request(line, config, default_val) do.
The config is a struct gpiod_line_request_config with three fields: consumer (the same label string), request_type (the direction, such as GPIOD_LINE_REQUEST_DIRECTION_INPUT), and flags (a bit mask of GPIOD_LINE_REQUEST_FLAG_* values). This fragment requests a button line as input with a pull-up:
struct gpiod_line_request_config cfg = {
.consumer = "m2s11a-button",
.request_type = GPIOD_LINE_REQUEST_DIRECTION_INPUT,
.flags = GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_UP,
};
if (gpiod_line_request(line, &cfg, 0) < 0) {
perror("gpiod_line_request");
gpiod_chip_close(chip);
return EXIT_FAILURE;
}
int value = gpiod_line_get_value(line);
if (value < 0)
perror("gpiod_line_get_value");
else
printf("line = %d\n", value);
The flags cover the properties introduced earlier. GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_UP and GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_DOWN enable the internal resistors; GPIOD_LINE_REQUEST_FLAG_BIAS_DISABLE switches them off. GPIOD_LINE_REQUEST_FLAG_ACTIVE_LOW declares the line active low. GPIOD_LINE_REQUEST_FLAG_OPEN_DRAIN and GPIOD_LINE_REQUEST_FLAG_OPEN_SOURCE select open-drain and open-source drive for outputs that must not push both rails. For an output you pass GPIOD_LINE_REQUEST_DIRECTION_OUTPUT as request_type, and default_val is the value driven as soon as the request succeeds.
Active state is the one subtle mapping. With no active-low flag, gpiod_line_set_value(line, 1) drives the wire high, and gpiod_line_get_value returns 1 for a high wire. With GPIOD_LINE_REQUEST_FLAG_ACTIVE_LOW, the library reverses the translation: logical 1 becomes the physical low level, and a physically low wire reads as logical 1. Your program keeps thinking in logical terms; only the mapping to the wire changes. Use it for signals whose on state is a low level, so the code reads naturally instead of inverting everywhere.
The same flags appear in the gpio tools (gpioget, gpioset and gpiomon), which the next lesson covers together with line events. For now the core loop is fixed: open the chip, get the line, request it with the right direction and flags, drive or sample it, then release it.
The next lesson, "GPIO line events and the gpio tools", answers how to wait for an edge on a line and how gpioget, gpioset and gpiomon let you exercise pins from the shell.
Key takeaways
- GPIO lines are requested through the /dev/gpiochipN character devices; the /sys/class/gpio interface is deprecated since Linux 4.8 but still buildable with CONFIG_GPIO_SYSFS.
- libgpiod 1.6 exposes gpiod_chip_open, gpiod_chip_get_line, gpiod_line_request_output and gpiod_line_request_input, plus gpiod_line_set_value and gpiod_line_get_value.
- A line reverts to its default state when the last process holding the device file descriptor exits.
- Active-low and bias flags translate logical values and provide pull-up or pull-down defaults.
Reflect
- Explain to a colleague, in two sentences: describe how a GPIO pin maps to a character device line and why the sysfs interface was deprecated.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Kernel documentationGPIO Userspace API
- Kernel documentationGPIO Character Device Userspace API
- Kernel documentationGPIO Sysfs Interface for Userspace (deprecated)
- Kernel documentationGeneral Purpose Input/Output (GPIO) driver API
Official documentation first. Links checked when the lesson was published.