The Complete Guide to GPIO, I2C and SPI From Linux Userspace
Drive GPIO lines, I2C sensors and SPI devices from Linux userspace with libgpiod, i2c-tools and spidev in C, Python and Rust, plus device tree and permissions.

A single-board computer running Linux gives you a rich operating system and, on its header pins, a set of electrical interfaces that look nothing like a laptop's: general-purpose input and output lines, an I2C bus for sensors and a SPI bus for faster peripherals. The question every newcomer asks is how to reach those pins from an ordinary program without writing a kernel driver. The answer is that Linux already exposes them to userspace through well-defined device nodes and a handful of libraries, and for a surprising range of projects that is all you need. A temperature logger, a relay controller, a display, an ADC reading a potentiometer and a button that triggers a photograph can all be done in a few dozen lines of C, Python or Rust.
This guide covers the three interfaces from the ground up on Linux 6.12 with libgpiod 2.1, i2c-tools 4.3 and the kernel's spidev driver. It explains what each interface is, how the kernel presents it, how to explore hardware from the shell, how to write programs against it in several languages, how the device tree and permissions fit in and how to decide when userspace is the right place for this code at all. It assumes you can use a shell and read C, and it defines hardware terms the first time they appear. The detailed posts on each tool are listed in the sections that use them.
How Linux presents hardware buses to a program
Linux separates a hardware controller, which the kernel drives, from the devices attached to it. A GPIO controller, an I2C controller and a SPI controller are each managed by a kernel driver that knows the SoC's registers. What a user program sees is a file in /dev, and it talks to the controller through system calls on that file. There are three such files for our three interfaces:
| Interface | Device node | Main API | What the node represents |
|---|---|---|---|
| GPIO | /dev/gpiochipN | ioctls, wrapped by libgpiod | A bank of pins, called a chip |
| I2C | /dev/i2c-N | ioctl, read, write | One I2C bus (adapter) |
| SPI | /dev/spidevB.C | ioctl, read, write | One chip-select on one SPI bus |
Notice what is not in the table: the individual peripheral. The kernel gives you the bus, and your program decides what to say to the device on it. That is the same relationship a network socket has to a remote server. It is also why userspace access is flexible and why it has limits. Nothing in the kernel knows that the thing on I2C address 0x48 is a temperature sensor, so nothing interprets its registers, manages its power or exposes its reading to other programs. If the kernel does have a driver for a chip, you should usually use that driver, a point the last section returns to.
Before starting, check that the kernel supports what you need. Three options matter: CONFIG_GPIO_CDEV for the GPIO character device, CONFIG_I2C_CHARDEV for /dev/i2c-N and CONFIG_SPI_SPIDEV for /dev/spidevB.C. Distribution kernels for popular boards enable them, and a Yocto or Buildroot kernel may not. The check is easy:
ls /dev/gpiochip* /dev/i2c-* /dev/spidev* 2>&1/dev/gpiochip0 /dev/gpiochip1
/dev/i2c-1
ls: cannot access '/dev/spidev*': No such file or directoryThis sample board has GPIO and I2C ready and needs SPI enabled in the device tree, which a later section handles.
GPIO: what a general-purpose pin is
A GPIO pin is a pin whose job is chosen by software. As an output, the program sets it to a logic high or low, which on a typical board means about 3.3 volts or about zero. As an input, the program reads whether the voltage at the pin is above or below a threshold. Most pins can also be switched to other functions, such as UART or I2C, through a multiplexer in the pin controller, and a pin used for another function is not available as a GPIO.
Three electrical details decide whether your first project works. First, current: a GPIO can source or sink only a few milliamps, so it drives an LED through a resistor and a transistor or a driver chip for anything larger, never a motor or a relay coil directly. Second, voltage: most application processors use 3.3 volts or lower, and applying 5 volts to a pin can damage the chip, so check the board's documentation and use a level shifter when interfacing 5 volt parts. Third, floating inputs: a pin connected to nothing reads random values, so inputs need a defined level through a pull-up or pull-down resistor, internal or external.
Chips, lines and offsets
The kernel groups GPIO pins into chips, one per controller, and numbers the pins within a chip as offsets starting from zero. A line is one pin, addressed as a chip and an offset, or by a name if the device tree provides one. The post on finding GPIO chips and lines with gpiodetect and gpioinfo has the full workflow, and the core of it is two commands:
gpiodetect
gpioinfo --chip gpiochip0 | head -6gpiochip0 [pinctrl-bcm2835] (54 lines)
gpiochip1 [raspberrypi-exp-gpio] (8 lines)
gpiochip0 - 54 lines:
line 0: "ID_SDA" input
line 1: "ID_SCL" input
line 2: "GPIO2" input
line 3: "GPIO3" inputThe output is from a Raspberry Pi and yours will differ. The value to take away is that line 2 on gpiochip0 is a particular pin whose name tells you where it is on the header. When the name is missing, the schematic and the SoC reference manual tell you.
Why not sysfs
Old tutorials control pins by writing numbers into /sys/class/gpio/export. That interface is deprecated, and the post on why the sysfs GPIO interface is deprecated lists the reasons: global numbers that change between kernels, pins that stay exported after a program crashes, races during setup, no atomic access to several lines and no support for bias, debounce or timestamps. The character device fixes each of those, and it is what libgpiod uses. Do not start new work on sysfs.
Ownership: a line belongs to a process
The most important idea in the character device is that you request lines, and the request is tied to a file descriptor. While the descriptor is open, the process owns the lines and nobody else can use them. When the process exits, normally or by crashing, the kernel releases them and restores their default state. This replaces a class of bugs with a rule that is easy to remember: the line is yours while your program is running. It also explains a surprise for people coming from sysfs. Setting a line with gpioset and exiting leaves nothing behind, because the owner is gone.
GPIO from the shell
The libgpiod command-line tools are the quickest way to verify wiring. Drive an LED on line 17:
gpioset --chip gpiochip0 17=1(the LED lights and the command keeps running until you press Ctrl-C)Read a button on line 27 with an internal pull-up:
gpioget --chip gpiochip0 --bias pull-up --numeric 271The post on toggling and reading GPIO lines with gpioset and gpioget covers timed pulses, several lines at once, active-low wiring and the busy error. Watch edges as they happen with gpiomon, which prints a line for each transition with a timestamp:
gpiomon --chip gpiochip0 --bias pull-up --edges both 271742311822.193450211 falling "27"
1742311822.342017745 rising "27"The values will differ on your board. gpiomon is a good first check that a button is wired the way you think and that its contact bounce is not producing a burst of events.
GPIO from Python, C and Rust
The tools are for the bench. A program needs the library. The same three operations, drive, read and wait for an edge, look similar in every language because they share the kernel's model: request lines with their settings, then use the request.
Python
The gpiod module of libgpiod 2 uses request_lines with a LineSettings object per line. A button read with a pull-up, as in the post on controlling GPIO lines from Python, is:
import gpiod
from gpiod.line import Bias, Direction, Value
with gpiod.request_lines(
"/dev/gpiochip0",
consumer="button-read",
config={27: gpiod.LineSettings(direction=Direction.INPUT, bias=Bias.PULL_UP)},
) as request:
print("released" if request.get_value(27) == Value.ACTIVE else "pressed")releasedThe with block guarantees the request closes. Python is good for scripts, test benches and slow control logic, and poor for anything that needs predictable timing.
C
The C API builds a request from small objects. The post on reading GPIO edge events in C with the libgpiod v2 API has the whole program. The shape is:
struct gpiod_chip *chip = gpiod_chip_open("/dev/gpiochip0");
struct gpiod_line_settings *s = gpiod_line_settings_new();
gpiod_line_settings_set_direction(s, GPIOD_LINE_DIRECTION_INPUT);
gpiod_line_settings_set_edge_detection(s, GPIOD_LINE_EDGE_BOTH);
gpiod_line_settings_set_debounce_period_us(s, 10000);
/* add the settings to a line config, request, then wait and read */If you meet code written for libgpiod 1.x, the post on porting from the v1 API to v2 maps every call across. The versions are not source compatible, and mixing them is the commonest source of confusing compile errors.
Rust
The gpio-cdev crate gives a typed API with RAII: the line is released when the handle is dropped. The post on accessing GPIO from Rust through the character device shows handles and event iteration. It uses the first version of the kernel interface, so use the libgpiod bindings if you need bias or debounce.
Edge events, debounce and timing
A button press is a transition, and the kernel can watch for it so your program sleeps until it happens. Request the line with edge detection, wait on the request's file descriptor and read events, each with a kernel timestamp taken at the interrupt. Mechanical contacts bounce for a few milliseconds, producing a burst of transitions for one press, so set a debounce period of about 10 milliseconds unless the switch datasheet says otherwise. User-space latency from interrupt to your program is typically tenths of a millisecond to a few milliseconds depending on load, and it is not bounded unless you use a real-time scheduling policy, so GPIO in userspace is right for buttons, status lights and slow handshakes, and wrong for generating a precise waveform or capturing a fast pulse train.
I2C: two wires and many devices
I2C is a bus with two shared signal lines, SDA for data and SCL for the clock, and a pull-up resistor on each. A controller starts every transaction and addresses one device among many by a 7-bit address. Because the wires are shared and open-drain, adding a sensor is a matter of connecting four wires: power, ground, SDA and SCL. Speeds are commonly 100 kHz or 400 kHz, which is plenty for sensors and configuration registers and too slow for bulk data.
A typical I2C device has a set of registers. To read one you write the register's number to the device and then read the data back; to write one you send the number followed by the data. The specification from NXP defines the signaling, and the datasheet of each device defines its registers and its address.
Enabling the bus
An I2C controller must be enabled in the device tree before /dev/i2c-N exists, and the pins have to be multiplexed to the I2C function. On many boards that is a line in the boot configuration. On a Raspberry Pi it is dtparam=i2c_arm=on in config.txt. Elsewhere it is a device tree overlay or a status = "okay" property on the controller node. Load i2c-dev if the character device support is a module.
Scanning and exploring
The post on scanning an I2C bus with i2cdetect shows how to read the address grid. The command and a sample result:
i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- 3c -- -- --
40: -- -- -- -- -- -- -- -- 48 -- -- -- -- -- -- -- A device at 0x48 answered. If your device is missing, work through power, pull-up resistors, level shifting, swapped wires and the 7-bit versus 8-bit address confusion, in that order. A cell showing UU means a kernel driver already holds that address.
Reading and writing registers
With the address known, the post on reading and writing I2C registers with i2cget, i2cset and i2ctransfer shows the commands. The most important lesson is that SMBus word commands return the low byte first, so a device that sends the high byte first, such as the TMP102 temperature sensor, comes out byte-swapped. i2ctransfer shows bytes in wire order and avoids the surprise:
i2ctransfer -y 1 w1@0x48 0x00 r20x19 0x00The TMP102 stores a 12-bit two's-complement temperature in the upper bits of that 16-bit value, where one count is 0.0625 degrees Celsius. The bytes 0x19 0x00 are 0x190 after shifting right by four, which is 400 counts and 25 degrees Celsius.
I2C from C
The post on talking to I2C devices in C through /dev/i2c-N and ioctl has complete programs. Open the node, select the device with I2C_SLAVE, then use write and read, or use a combined transaction with I2C_RDWR when the device needs a repeated start:
int fd = open("/dev/i2c-1", O_RDWR);
ioctl(fd, I2C_SLAVE, 0x48);
uint8_t reg = 0x00, buf[2];
write(fd, ®, 1);
read(fd, buf, 2);
int raw = (((buf[0] << 8) | buf[1]) >> 4);This is the entire protocol for a simple sensor. Add error checks on every call in real code, since a device that does not acknowledge makes write or read fail with an errno that distinguishes a wiring problem from a bus problem.
I2C from Python and Rust
Python has smbus2, a library that wraps the same ioctls with methods like read_i2c_block_data. Rust has the i2cdev crate. Both follow the pattern of opening the node and addressing the device. Prefer calls that do a register read as one combined transaction, because two separate calls leave a window in which another program can change the device's register pointer, and some devices need the repeated start.
Pitfalls specific to I2C
The bus can hang. If a device holds SDA low, for example after a reset in the middle of a transfer, every transaction fails until the device is released, and the controller driver may recover with extra clock pulses or may not. Keep wiring short and pull-ups in the 2 to 10 kilohm range for the standard speeds. Devices with the same fixed address cannot share a bus, which is solved with address pins, a different bus or a multiplexer chip. And remember power sequencing: a sensor that is powered off but connected to a bus with pull-ups can load the lines and corrupt traffic to others.
SPI: faster, with chip selects
SPI uses four signals: a clock, data out from the controller (MOSI), data in (MISO) and a chip-select line for each device. The controller asserts a device's chip select, clocks bits out on MOSI and in on MISO at the same time, and releases the chip select. There are no addresses and no acknowledgments: the device is selected by its dedicated line, and the protocol of the bytes is defined by the device. Speeds range from hundreds of kilohertz to tens of megahertz, so SPI suits displays, ADCs, flash chips and radios.
The details that must match the device are the mode, the clock speed and the word size. Mode is two bits, clock polarity (CPOL) and clock phase (CPHA), which define when the data is sampled relative to the clock edge. Mode 0 means the clock idles low and data is sampled on the rising edge, and it is the most common. The datasheet states the required mode, the maximum clock frequency and whether the most significant bit goes first.
Enabling spidev
The kernel exposes /dev/spidevB.C, where B is the bus and C the chip select, only if a device tree node on that bus binds to the spidev driver. The node names a compatible string the driver recognizes. In a device tree overlay, for a device on chip select 0:
&spi0 {
status = "okay";
#address-cells = <1>;
#size-cells = <0>;
adc@0 {
compatible = "rohm,dh2228fv";
reg = <0>;
spi-max-frequency = <1000000>;
};
};The compatible string rohm,dh2228fv is one of the identifiers the spidev driver accepts as a generic user-space binding; the kernel logs a warning if you use an unknown one, so check drivers/spi/spidev.c for the list in your kernel version. Many boards ship overlays or configuration switches for this, such as dtparam=spi=on on a Raspberry Pi. After booting, ls /dev/spidev* shows the node.
Test with a loopback
Before wiring a real device, connect MOSI to MISO with a jumper. Whatever you send comes back. The kernel source includes a test program, spidev_test, in tools/spi/, and a successful loopback prints the same bytes in and out:
spidev_test -D /dev/spidev0.0 -s 1000000 -p "hello"spi mode: 0x0
bits per word: 8
max speed: 1000000 Hz (1000 KHz)
TX | 68 65 6C 6C 6F | hello
RX | 68 65 6C 6C 6F | helloIf RX is all zeros or all ones, the loopback jumper is missing or the pins are not in SPI mode.
SPI from C
The interface is one ioctl, SPI_IOC_MESSAGE, that performs a full-duplex transfer described by struct spi_ioc_transfer. This program reads channel 0 of an MCP3008 ADC, a 10-bit eight-channel part that is a common first SPI device. The chip expects three bytes: a start bit, then the single-ended channel selection in the upper nibble, then a don't-care byte; it returns the result in the low two bits of the second byte and all of the third:
#include <fcntl.h>
#include <linux/spi/spidev.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
int main(void)
{
int fd = open("/dev/spidev0.0", O_RDWR);
if (fd < 0) {
perror("open");
return 1;
}
uint8_t mode = SPI_MODE_0;
uint8_t bits = 8;
uint32_t speed = 1000000;
ioctl(fd, SPI_IOC_WR_MODE, &mode);
ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
uint8_t tx[3] = { 0x01, (uint8_t)((8 + 0) << 4), 0x00 };
uint8_t rx[3] = { 0 };
struct spi_ioc_transfer t;
memset(&t, 0, sizeof t);
t.tx_buf = (unsigned long)tx;
t.rx_buf = (unsigned long)rx;
t.len = 3;
t.speed_hz = speed;
t.bits_per_word = bits;
if (ioctl(fd, SPI_IOC_MESSAGE(1), &t) < 0) {
perror("SPI_IOC_MESSAGE");
close(fd);
return 1;
}
int raw = ((rx[1] & 0x03) << 8) | rx[2];
printf("raw=%d (%.2f V)\n", raw, raw * 3.3 / 1024.0);
close(fd);
return 0;
}raw=512 (1.65 V)With the input at half the 3.3 volt reference the reading is about 512 counts. The exact number on your board will vary with the signal. The three bytes are transferred in one chip-select assertion, because one struct spi_ioc_transfer is one continuous transaction; several structures in one SPI_IOC_MESSAGE(n) call keep the chip select asserted across them unless you set cs_change.
SPI from Python
The spidev module wraps the same device node. It is the shortest path to a working ADC read:
import spidev
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 1000000
spi.mode = 0
reply = spi.xfer2([0x01, (8 + 0) << 4, 0x00])
raw = ((reply[1] & 0x03) << 8) | reply[2]
print(f"raw={raw}")
spi.close()raw=512xfer2 keeps the chip select asserted for the whole list, which is what the ADC needs. xfer may toggle it between bytes on some controllers.
Pitfalls specific to SPI
A wrong mode produces plausible but wrong data, such as readings shifted by one bit, which is hard to see without the datasheet's timing diagram next to your mode setting. A clock faster than the device or the wiring supports corrupts data silently, and long jumper wires limit the practical speed on a breadboard. Chip select handling is controller specific: when you use the hardware chip selects, the controller drives them; when you use a GPIO as chip select through the device tree's cs-gpios, the driver toggles it. Do not drive a chip select from your own program through GPIO unless you have removed it from the SPI controller's control.
Device tree and permissions
Two pieces of system configuration decide whether any of this works for an ordinary user.
The device tree
The device tree is a description of the hardware that the bootloader hands to the kernel. For our purposes it does three things. It enables the controllers (status = "okay"), it configures pin multiplexing so that pins serve the right function, and it describes the devices on each bus, which for spidev means the generic binding shown above. For GPIO it can also name lines with gpio-line-names, which makes your code readable and independent of offsets. When something does not appear in /dev, the device tree is the first place to look, and dtc -I fs /proc/device-tree or the files under /sys/firmware/devicetree/base/ show what the running kernel was told.
Permissions
The nodes are owned by root by default, so a normal user gets "Permission denied". Create groups and a udev rule to grant access to those who need it:
SUBSYSTEM=="gpio", KERNEL=="gpiochip*", GROUP="gpio", MODE="0660"
SUBSYSTEM=="i2c-dev", GROUP="i2c", MODE="0660"
SUBSYSTEM=="spidev", GROUP="spi", MODE="0660"Save the rules in /etc/udev/rules.d/60-hardware.rules, reload with udevadm control --reload, and add your service's user to the groups. A systemd service can use SupplementaryGroups= instead of a login group, and DeviceAllow= to restrict a sandboxed service to exactly the nodes it needs. Access to these nodes is access to hardware, so grant it narrowly: a program with write access to an I2C bus can reconfigure every device on it, including power management chips.
Choosing userspace or a kernel driver
Userspace access is the right tool for many jobs and the wrong one for some. The decision rests on what else needs the device.
Use userspace when no kernel driver exists for the chip, when you are prototyping, when a single program owns the device and when the timing demands are modest. A custom board with a one-off sensor is the classic case.
Use a kernel driver when one exists. A TMP102 has an in-tree driver that exposes its temperature through hwmon, handles alert pins and power state, and can be read by any program from /sys/class/hwmon/. Standard classes also integrate with the rest of the system: LEDs appear under /sys/class/leds/, buttons become input events, ADCs appear in the industrial I/O subsystem, and displays and flash chips mount as devices. Using the driver avoids two programs fighting over one device and gives you correct power management for free. If a driver exists but is not bound, add the device to the device tree with its proper compatible string instead of using spidev or i2c-dev.
Use a kernel driver, or a real-time core, when timing is tight. User space on Linux does not guarantee latency. Toggling a pin at a fixed rate, capturing a pulse width or bit-banging a protocol with microsecond tolerances needs a hardware timer, a PWM or capture peripheral, a PRU or a microcontroller, and the Linux side should send it commands rather than trying to do the timing itself.
Putting it together: a small project
A concrete example shows how the pieces combine. The goal is a program that reads a TMP102 over I2C every second, lights an LED on GPIO 17 when the temperature exceeds a threshold, and logs a message when a button on GPIO 27 is pressed. It needs all three kinds of access except SPI, and its structure is a loop that waits on several file descriptors: a timer for the sensor, and the button's GPIO event descriptor.
The design choices follow from the sections above. The LED line is requested once at startup as an output and held for the program's life. The button is requested with both edges and a debounce period, and its request descriptor goes into poll next to a timerfd. The temperature read is one I2C_RDWR transaction. On any I2C error the program logs the errno and tries again on the next tick, because a transient bus error should not stop an appliance. A systemd unit runs it as an unprivileged user in the gpio and i2c groups, with DeviceAllow= for just those nodes, and restarts it on failure.
Run it by hand first, look at what gpioinfo reports for the consumer names while it runs, and verify behavior with the tools you already know: toggle the sensor's input by warming it, press the button and compare the program's log timestamps with gpiomon on a second terminal, which fails with a busy error if your program owns the line, and that error is itself the confirmation that ownership works.
Troubleshooting checklist
Most problems come from a short list of causes, and checking them in order saves time.
| Symptom | Check |
|---|---|
/dev/gpiochipN, /dev/i2c-N or /dev/spidevB.C missing | Kernel option enabled? Controller enabled in the device tree? Module loaded? |
| Permission denied | Group and udev rule, or run once as root to confirm the cause |
| Line request fails with busy | Run gpioinfo and read the consumer; a kernel driver or another process holds it |
| Output has no effect on the pin | Pin muxed to another function? Wrong chip or offset? Measure with a meter |
| Input reads random values | No pull resistor; set bias or add an external resistor |
| I2C scan finds nothing | Power, pull-ups, level shifting, wiring, 7-bit address, correct bus number |
| I2C data looks swapped | SMBus word byte order; use i2ctransfer or swap the bytes |
| SPI returns all zeros or all ones | Loopback test; check mode, wiring, chip select and that the device is powered |
| SPI data is shifted by a bit | Wrong SPI mode; compare with the datasheet timing diagram |
| Works as root, fails as service | Supplementary groups, DeviceAllow=, sandbox options in the unit |
An oscilloscope or a cheap logic analyzer turns many of these from guesses into observations. Seeing the clock and data lines for a failing transfer settles questions about mode, address and acknowledgment immediately.
Where this guide stops
This guide stays in userspace and on the three most common buses. UART, PWM, ADC through the industrial I/O subsystem, one-wire devices and CAN are related and have their own interfaces. Writing a kernel driver for a device, either with the in-kernel I2C and SPI client APIs or with the industrial I/O framework, is the next step when a userspace program grows into something that other programs should share. And production devices need the supporting pieces covered elsewhere in this series: a read-only root, supervised services, a watchdog and an update mechanism.
Reading a datasheet for these buses
Every interface in this guide is only half specified by the kernel. The other half is the datasheet of the chip on the other end, and the same short checklist applies whether the chip is a sensor, an expander or a display driver. For an I2C part, find the 7-bit address and the pins that change it, the register map with each register's width and reset value, the byte order of multi-byte registers, the maximum bus speed and the time the device needs after power-up or after a conversion before its data is valid. For a SPI part, find the required mode, the maximum clock frequency, the bit order, the exact byte sequence of a command and whether the chip select must stay low across the whole command. For a GPIO-connected part, such as a relay driver or a status LED, find the active level, the maximum current per pin and whether the line needs a pull resistor at reset.
Two habits save most of the debugging time. Write the register values you intend to use as named constants in your program, with the datasheet page in a comment, so the next reader can check them. And read an identification register first when the chip has one. A wrong ID byte tells you immediately that the address, the mode or the wiring is wrong, before you spend an hour on the application logic. Many I2C parts have a device or manufacturer ID register, and many SPI flash chips answer a read-ID command, which makes this a cheap first test.
Wiring, levels and electrical safety
Software errors are easy to fix. Electrical errors can destroy the board, so treat the wiring as part of the design. Check the logic level of every part on a bus. A 3.3 volt controller connected to a 5 volt device without a level shifter can be damaged by the device's output, and a 5 volt controller connected to a 3.3 volt device can damage it. I2C is open-drain and needs pull-up resistors to a single supply voltage, so a mixed-voltage bus uses a bidirectional level shifter designed for open-drain signals, not a simple resistor divider. SPI and GPIO signals are push-pull, and a unidirectional shifter or a divider can work for slow signals.
Keep wires short, especially for SPI at high clock rates and I2C at 400 kHz, where long jumper wires add capacitance that rounds the edges until data is corrupted. Share a ground between every board on the bus. Do not draw power for loads from a GPIO pin. Add a series resistor, commonly a few hundred ohms to a kilohm, between a GPIO and an LED, and drive relays, motors and anything inductive through a transistor or a driver chip with a flyback diode. When a project misbehaves in odd ways, a multimeter and a scope or logic analyzer are better tools than another round of code changes, because they show whether the signal ever left the pin.
Running hardware code as a service
A program that works from your shell has to survive reboots, crashes and the absence of a login session once it is part of a product. Run it under systemd as an unprivileged user with exactly the access it needs. A unit for the small project described earlier looks like this:
[Unit]
Description=Sensor and LED controller
After=multi-user.target
[Service]
ExecStart=/usr/local/bin/sensord
User=sensord
Group=sensord
SupplementaryGroups=gpio i2c
Restart=on-failure
RestartSec=2s
DevicePolicy=closed
DeviceAllow=/dev/gpiochip0 rw
DeviceAllow=/dev/i2c-1 rw
ProtectSystem=strict
NoNewPrivileges=yes
[Install]
WantedBy=multi-user.targetSupplementaryGroups= grants the group permissions that the udev rules set on the device nodes. DevicePolicy=closed with DeviceAllow= entries restricts the service to the nodes it lists, so a compromise of this program cannot reach other buses. Restart=on-failure brings it back after a crash, and because the kernel releases the GPIO lines when the process dies, the restarted program can request them again without cleanup. If the program should be restarted when it hangs, as opposed to crashing, add a watchdog as described in the post on supervising a daemon with WatchdogSec.
Think about the state of the hardware when the service is stopped. A relay line returns to its default state when the process exits, and for most SoCs that default is an input with no drive, which might leave a relay released or an LED dark. If a stopped service must leave a device in a safe condition, make sure the circuit has a pull resistor that defines it, and do not rely on the last value written. The same holds for a crash, and a crash is the case you will not be there to handle.
Testing without the hardware
Software that talks to hardware needs tests that run on a development machine and in continuous integration. Linux provides simulators for each interface. The gpio-sim kernel module creates simulated GPIO chips through configfs, so you can run libgpiod programs and the command-line tools against lines whose values you control from a script. The i2c-stub module creates an I2C adapter with a fake device at an address you choose, whose registers you can preload with i2cset, which is enough to test a driver or a program that reads a sensor. For SPI, the loopback test with MOSI wired to MISO, or the spi-loopback-test module, checks the plumbing, and a unit test can hide the SPI transfer behind a function that a test double replaces.
The most useful structure is a thin layer between your logic and the device. Write the application against an interface with operations such as set the LED, read the temperature and wait for the button, implement it once against the real nodes and once as a fake, and test the logic with the fake. Reserve the real-hardware tests for the thin layer, run them on a bench board, and keep them short. That structure also makes the rest of the code independent of whether the pin is a GPIO today and an expander line tomorrow.
From prototype to product
A bench script becomes a product when it handles the things that never happen at the bench. It must start when the bus is not ready yet, so retry the first access with a bound. It must tolerate a sensor that disappears, reporting a fault instead of crashing. It must release hardware cleanly on shutdown. It must log enough to diagnose a field problem, without logging a line per sample to flash. And it must cooperate with the rest of the image: a read-only root, state in the right directories and a watchdog. Each of these is a small change, and together they are the difference between a demo and a device.


