
Recall first from The reproducible build loop and advanced debugging
- Reproducible builds need fixed timestamps and path maps, which also makes ccache hits more likely.
- One script that builds, deploys and starts gdbserver turns a ten-step ritual into a habit.
- A core file pairs with the exact binary and libraries that crashed, matched by build-id, so the debug archive must be kept.
Why a hardware abstraction layer exists
3 min readThe previous lesson showed how to cross-compile and run a build on the target board. This lesson answers why that program needs a hardware abstraction layer, how Linux exposes the hardware it touches, and how you drive GPIO from user space.
A product that starts on a Raspberry Pi prototype often ships on a custom carrier board with a different SoC, a different pin-out and different sensors. If your application code is full of board-specific details, a board change means rewriting the code. A a software layer that defines a stable interface for hardware operations so higher code never touches hardware directly, or HAL, stops that. It gives the application a small vocabulary of operations such as read_sensor and set_output, and every board supplies a backend that implements them.
A HAL earns its keep in three ways. First, portability: the same application logic runs on any board that provides a backend. Second, testability: you can build the application on a fast host with a a stand-in object that implements an interface with canned or recorded behaviour, used in place of real hardware in tests backend, so the whole logic is exercised without touching a board. Third, parallel development: one person writes the application against the interface while another brings up the real backend, because the interface was agreed first. That third point is the discipline behind the whole lesson: interface-first design. Write the interface before you write either implementation, and every decision after that becomes replaceable.
The cost of a HAL is indirection: one more layer, one more function call, sometimes a virtual call. On an embedded target that cost is almost always invisible next to the actual I/O, and later sections measure it rather than guess. The alternative, a product where the logic and the board details are one entangled blob, is what you inherit when a prototype is hurried into production, and it is the single biggest reason an embedded codebase cannot be tested on a host.
A GPIO miswired to 5 V can destroy a 3.3 V board. Prototype the logic against a mock first, and only attach real electronics once the software is known good and the voltage levels are checked.
The Linux device model from user space
2 min readBefore you can abstract hardware you must see it the way Linux exposes it. Linux turns hardware into files, in two different flavours. A a special file in /dev that represents a device; the kernel routes I/O on it to a driver identified by major and minor numbers is a file you can open, read and write, such as /dev/i2c-1 or /dev/input/event0. Each node carries a major number that selects a driver and a minor number that selects an instance, visible in the ls -l listing as two numbers before the date. The same idea appears everywhere: /dev/ttyAMA0 has major 204 and minor 64, and /dev/ttyAMA1 has the same major with minor 65 because one driver serves all four UARTs.
Devices split into three kinds. A a device accessed as an unbuffered byte stream through a node, the usual choice for custom hardware does unbuffered read and write, which is why device code avoids stdio buffering and calls open, read and write directly. Block devices add a heavy buffering layer for mass storage. Network devices have no node at all; you reach them through sockets. The important one here is the character device, because GPIO, I2C, SPI and input all appear as character devices or files under sysfs.
The other flavour is a virtual filesystem mounted at /sys that exposes kernel objects, device attributes and their relationships as files and directories. Where /dev gives you a stream, /sys gives you named attributes to read and write, one value per file. /sys/class groups devices by function (tty, gpio, leds, pwm), /sys/bus groups them by bus (i2c, spi, usb), and /sys/devices shows the physical topology. A single device therefore has two faces: an openable node in /dev and a set of attributes in /sys, and udev uses the latter to create and configure the former.
The escape hatch that ties them together is the ioctl system call, ioctl(fd, request, arg), which sends a driver-specific command and pointer to a device. When read and write are too thin, ioctl carries a structured command, which is exactly how I2C and SPI transactions reach user space. The rest of this lesson walks each interface: GPIO, I2C, SPI, PWM, LEDs, input events, then how you discover the right node and lock all of it behind a HAL.
GPIO from user space: libgpiod and the character device
4 min readgeneral-purpose input/output: an individual digital pin that you can configure as an input or an output and read or drive high or low is the simplest hardware interface, used for LEDs, buttons, relays and simple sensors. There are two ways to reach GPIO from user space, and only one of them is current.
The legacy interface is sysfs. Writing a global GPIO number to /sys/class/gpio/export creates a /sys/class/gpio/gpioN directory, whose direction, value, edge and active_low files you then read and write. It works, but it is deprecated since kernel 4.8 (2016), and it has structural flaws: lines are identified by a global number that varies between boards, a line must be exported and unexported by hand and stays exported if a process dies, and there is no way to claim several lines atomically. The current interface is the character device /dev/gpiochipN, one node per GPIO controller, where you request lines by a stable offset within that chip.
The tool and library for that interface is libgpiod, a userspace library and command suite (gpiodetect, gpioinfo, gpioset, gpioget, gpiomon) for the GPIO character device. The tools are the fastest way to confirm a pin works:
gpiodetect # one chip per GPIO controller, with label and line count
gpioinfo gpiochip0 # per line: offset, name, consumer, direction, flags
gpioset gpiochip0 4=1 # drive line 4 high; held until the command ends
gpioget gpiochip0 17 # read line 17
gpiomon gpiochip0 17 # print timestamped events as line 17 changes
gpiofind led0 # find which chip and offset carry a named line
gpiodetect prints one line per chip, for example a chip labelled pinctrl-bcm2835 with its line count; the exact names and counts depend on your board. gpioinfo shows, for each line, its offset, an optional device-tree name, the consumer that holds it if any, and its direction. These two are your first move whenever a pin seems dead, because they tell you which chip and offset a pin actually is, which is rarely the number printed on the silkscreen.
The C API follows the same model. libgpiod 2.0 (2022) changed the object model to request handles, but the widely documented 1.x names below remain the easiest to read; the tools are identical in both versions:
#include <gpiod.h>
#include <unistd.h>
int main(void)
{
struct gpiod_chip *chip = gpiod_chip_open("/dev/gpiochip0");
struct gpiod_line *led = gpiod_chip_get_line(chip, 4);
struct gpiod_line *btn = gpiod_chip_get_line(chip, 17);
gpiod_line_request_output(led, "led-demo", 0);
gpiod_line_request_input(btn, "led-demo");
for (int i = 0; i < 5; i++) {
gpiod_line_set_value(led, 1);
usleep(500000);
gpiod_line_set_value(led, 0);
usleep(500000);
}
gpiod_line_release(led);
gpiod_line_release(btn);
gpiod_chip_close(chip);
return 0;
}
Build it with gcc blink.c -o blink -lgpiod. The pattern is the lifecycle every backend must respect: open a chip, request lines with a consumer name, use them, release them, close the chip. The consumer string matters, because gpioinfo reports it, and that is how you prove a line belongs to your process rather than to another service.
Open the chip: gpiod_chip_open gives a handle to one /dev/gpiochipN controller
Select lines: gpiod_chip_get_line names a line by offset within that chip
Request: gpiod_line_request_output or _input claims the line for a consumer
Use: set or get the value, or wait for edge events
Release: gpiod_line_release returns the line to the pool
Close: gpiod_chip_close frees the controller handle
Going deeperWhy the sysfs GPIO interface was retired
The sysfs interface could not be fixed because its model was wrong at the root. A global GPIO number is an unstable identifier: the same physical pin is a different number on a different board, and even on one board the mapping depends on probe order. Export and unexport are not reference-counted, so two programs can race over the same line, and a crashed process leaves a line exported forever. Most seriously, each direction or value write is a separate file write, so setting several lines together cannot be atomic; a program that needs two pins to change in the same instant simply cannot express that. The character device fixes all three: lines are addressed by chip and offset, requests are kernel objects that are released automatically when their file descriptor closes, and one ioctl can request a bulk of lines atomically.
Key takeaways
- A HAL isolates business logic from hardware specifics, so the same code runs on different boards and under test on a host.
- Linux exposes hardware as files: device nodes for byte-stream devices and sysfs attributes for simple knobs.
- libgpiod and the /dev/gpiochipN character device replace the deprecated sysfs GPIO interface.
- A libgpiod backend follows an open, request, use, release, close lifecycle, and the consumer string proves a line belongs to your process
Reflect
- Explain to a colleague, in two sentences: explain why a hardware abstraction layer makes an application portable and testable without hardware
- 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
Official documentation first. Links checked when the lesson was published.