The Complete Guide to I2C and SPI Drivers on Linux
One driver for one chip, built from user-space probing to a regmap core with I2C and SPI front ends, IIO output, interrupts, error handling and debugging.

Sooner or later, every embedded Linux developer meets a chip on a two-wire or four-wire bus and has to make it a first-class citizen of the system: a temperature sensor, an ADC, an EEPROM, a codec, a display controller. The work is rarely the chip's protocol itself. It is knowing where each piece belongs: which layer owns the bus, which describes the device, how registers are accessed, how values reach user space, what to do when a transfer fails. This guide builds a single driver for a single imaginary chip, an environment sensor sold in both an I2C and an SPI package, and it takes the code from the first command at a shell prompt to a shared core with two bus front ends, standard IIO output, an interrupt handler, error handling and a debugging routine. At the end it descends one layer and shows what the controller drivers underneath look like. The guide follows Linux 6.12 and GCC 14, and the facts about APIs come from the kernel's I2C, SPI, regmap and IIO documents. As everywhere on this site, code is written with care and never executed, so output blocks are worked out from the source and every address, value and timestamp is an example.
The shorter posts in this cluster each take one step in depth: the two buses explained, user-space access, the Raspberry Pi switches, a client driver, regmap, SMBus against raw transfers, interrupts, NACK handling, instantiation, hwmon, tracing, IIO, and the two controller drivers. This guide is the route through all of them. The companion guide on platform drivers and device tree covers the layer that the controllers themselves sit on.
The chip we are driving
The imaginary part is called acme,env100. It measures temperature, and it comes in an 8-pin package with an I2C interface at address 0x48 or 0x49, and in a 10-pin package with SPI mode 0 up to 5 MHz. Its register file is the same on both buses, and it has all the details that make a real driver non-trivial:
| Register | Name | Contents |
|---|---|---|
0xD0 | ID | Fixed value 0x58 |
0xF3 | STATUS | Bit 0 conversion running, bit 1 alert |
0xF4 | CTRL | Bits 1:0 mode (0 sleep, 1 one shot, 3 continuous), bit 2 alert enable |
0xF8 | TEMP_MSB | High byte of the temperature |
0xF9 | TEMP_LSB | Low byte; the pair is a signed 16-bit value, 1/128 degree Celsius per count |
0xFA | THIGH_MSB | High limit, same format; two bytes |
On I2C a register read is a write of the register number followed by a repeated start and a read. On SPI the register address goes out with bit 7 set for a read and clear for a write, and the data follows in the same chip-select assertion. The chip has an open-drain alert pin that goes low when the temperature exceeds the high limit. Everything in this guide happens in service of reading that temperature correctly and reporting it the way Linux expects.
Two buses, two models
Before the driver, the wires. I2C uses two open-drain lines shared by every device on the bus: SDA for data and SCL for the clock, with pull-up resistors returning them high. The controller starts a transfer by pulling SDA low while SCL is high, sends a 7-bit address and a direction bit, and the addressed target acknowledges by pulling SDA low for one clock. Data bytes follow, each acknowledged by the receiver, and a stop condition ends the transfer. Because addressing and acknowledgment are in the protocol, a NACK tells you something: nobody answered the address, or the target refused a byte. Standard speeds are 100 kHz, 400 kHz and 1 MHz, and a target may hold SCL low to make the controller wait, which is clock stretching.
SPI has no addressing and no acknowledgment. It uses a clock, two data lines (controller out and controller in) and one chip select per device. Selecting a device means pulling its select line low, and from then on every clock edge shifts one bit out and one bit in at once, so every transfer is full duplex whether or not both directions carry meaning. Because there is no standard framing, each chip defines its own: which clock polarity and phase, which bit order, how a command and its reply are laid out. That is why an SPI driver always begins with the datasheet's timing diagram, and why the reply to a command arrives one byte late, clocked in during the byte after the command.
The practical comparison is short. I2C costs two pins for any number of devices, tops out around 1 MHz and gives you acknowledgment. SPI costs three shared pins plus a select per device, runs at tens of megahertz and gives you speed and simplicity. Many chips, including ours, offer both. The Linux model is the same for each bus: a controller driver operates the SoC's bus hardware and registers a bus with the core, and a client driver knows one chip and talks to it through the core's API without ever touching the controller. The device model joins them: children of the controller, described in firmware, become client devices, and the core matches each with a client driver.
Bring-up from user space first
Do not write a line of kernel code until you can talk to the chip from a shell. It proves the power, the wiring, the address and your reading of the datasheet, and it leaves you with a list of commands that become your driver's initialization.
For I2C, load i2c-dev, which exposes each adapter as a device node, and use i2c-tools:
sudo modprobe i2c-dev
i2cdetect -l
i2cdetect -y 1
i2cget -y 1 0x48 0xd0i2c-1 i2c bcm2835 (i2c@7e804000) I2C adapter
0 1 2 3 4 5 6 7 8 9 a b c d e f
40: -- -- -- -- -- -- -- -- 48 -- -- -- -- -- -- --
0x58The scan finds a device at 0x48, and reading register 0xD0 returns 0x58, the chip's fixed ID. That single read proves the address, the bus speed and the power. If the table is empty, suspect wiring or pull-ups. If a cell shows UU, a kernel driver already owns that address. If i2cget returns 0xff for everything, the chip is not answering and the bus floats high.
For SPI, the spidev driver exposes /dev/spidevB.C, and a short C program configures mode and speed with ioctl and exchanges bytes with SPI_IOC_MESSAGE. Reading the ID register means sending the address with bit 7 set and one dummy byte, and the answer arrives in the second received byte:
#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)
{
uint8_t mode = SPI_MODE_0, bits = 8;
uint32_t speed = 1000000;
uint8_t tx[2] = { 0xD0 | 0x80, 0x00 }, rx[2] = { 0 };
struct spi_ioc_transfer xfer = {
.tx_buf = (unsigned long)tx,
.rx_buf = (unsigned long)rx,
.len = 2,
.speed_hz = speed,
.bits_per_word = bits,
};
int fd = open("/dev/spidev0.0", O_RDWR);
if (fd < 0 || ioctl(fd, SPI_IOC_WR_MODE, &mode) < 0 ||
ioctl(fd, SPI_IOC_MESSAGE(1), &xfer) < 0) {
perror("spi");
return 1;
}
printf("id=0x%02x\n", rx[1]);
close(fd);
return 0;
}id=0x58The same ID appears over the other bus, which confirms the mode and wiring. A loopback jumper from MOSI to MISO with no chip attached is the way to separate controller problems from chip problems, using the kernel's spidev_test tool. All of this needs the buses enabled, which on a Raspberry Pi means dtparam=i2c_arm=on and dtparam=spi=on in /boot/firmware/config.txt on Bookworm images, followed by a reboot, and on other boards means enabling the controller nodes in the device tree.
Telling the kernel the chip exists
Neither bus can enumerate its devices, so something must declare the chip. The description is the same idea as for any non-discoverable device. For our sensor the board's device tree has a child node under each controller, with reg as the I2C address or the SPI chip select:
&i2c1 {
status = "okay";
clock-frequency = <400000>;
env@48 {
compatible = "acme,env100";
reg = <0x48>;
interrupt-parent = <&gpio>;
interrupts = <17 IRQ_TYPE_LEVEL_LOW>;
};
};
&spi0 {
status = "okay";
env@0 {
compatible = "acme,env100";
reg = <0>;
spi-max-frequency = <5000000>;
interrupt-parent = <&gpio>;
interrupts = <27 IRQ_TYPE_LEVEL_LOW>;
};
};You would use only one of the two on a real board. The compatible string is the same, because it names the chip, not the bus, and the bus driver is chosen by where the node sits. On x86 and other ACPI machines the same device appears in the firmware's tables with a hardware ID and an I2cSerialBus or SpiSerialBus resource, and the core creates the client the same way. On a Raspberry Pi, the node is added with an overlay and dtoverlay= in config.txt, because the firmware merges overlays into the base tree before the kernel starts.
For quick tests without editing the tree, I2C has a sysfs shortcut. Writing a driver name and address to the adapter's new_device file creates a client, and delete_device removes it:
echo env100 0x48 | sudo tee /sys/bus/i2c/devices/i2c-1/new_device
echo 0x48 | sudo tee /sys/bus/i2c/devices/i2c-1/delete_deviceenv100 0x48
0x48The name must match an i2c_device_id entry in the driver, which is one reason to always provide that table. The device disappears at reboot, so use this for development only. Creating a client does not probe for the chip: the core never checks that anything answers at the address, so a driver's first duty in probe is to read the ID register and refuse to bind when it is wrong.
The architecture: a shared core and two thin front ends
Because the chip speaks the same registers on both buses, the right structure is three files. A core file holds everything that knows the chip: register definitions, the IIO channels, reading and converting the temperature, the interrupt handler. An I2C file and an SPI file each hold the few lines that create a register map for their bus and call the core. Kernel drivers for chips that come in both flavors are laid out this way, and the glue between them is regmap.
Regmap is the kernel's register access layer. You describe the register file once, in a struct regmap_config, and create a map for a bus with one call. After that, regmap_read, regmap_write and regmap_update_bits work the same whichever bus is underneath, and you get locking, an optional cache and a debugfs dump for free. The core then has no idea which bus it is on.
#ifndef ENV100_H
#define ENV100_H
#include <linux/regmap.h>
#define ENV100_REG_ID 0xd0
#define ENV100_REG_STATUS 0xf3
#define ENV100_REG_CTRL 0xf4
#define ENV100_REG_TEMP 0xf8
#define ENV100_REG_THIGH 0xfa
#define ENV100_ID_VALUE 0x58
#define ENV100_CTRL_MODE GENMASK(1, 0)
#define ENV100_CTRL_ALERT BIT(2)
#define ENV100_MODE_CONT 3
#define ENV100_STATUS_ALERT BIT(1)
extern const struct regmap_config env100_regmap_config;
int env100_core_probe(struct device *dev, struct regmap *map,
const char *name, int irq);
#endifThe shared register map configuration lives in the core and is exported to the front ends:
#include <linux/bitfield.h>
#include <linux/iio/iio.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/regmap.h>
#include "env100.h"
static bool env100_volatile_reg(struct device *dev, unsigned int reg)
{
return reg == ENV100_REG_STATUS || reg == ENV100_REG_TEMP ||
reg == ENV100_REG_TEMP + 1;
}
const struct regmap_config env100_regmap_config = {
.reg_bits = 8,
.val_bits = 8,
.max_register = ENV100_REG_THIGH + 1,
.volatile_reg = env100_volatile_reg,
.cache_type = REGCACHE_MAPLE,
};
EXPORT_SYMBOL_GPL(env100_regmap_config);The two temperature registers and the status register change on their own, so they are volatile and never served from the cache. Everything else, the control register and the limit, can be cached.
The I2C front end
The I2C file is short, as it should be. It creates the map and calls the core. Both a device tree match table and an i2c_device_id table are present:
#include <linux/i2c.h>
#include <linux/mod_devicetable.h>
#include <linux/module.h>
#include <linux/regmap.h>
#include "env100.h"
static int env100_i2c_probe(struct i2c_client *client)
{
struct regmap *map;
map = devm_regmap_init_i2c(client, &env100_regmap_config);
if (IS_ERR(map))
return dev_err_probe(&client->dev, PTR_ERR(map),
"regmap init failed\n");
return env100_core_probe(&client->dev, map, "env100", client->irq);
}
static const struct of_device_id env100_i2c_of_match[] = {
{ .compatible = "acme,env100" },
{ }
};
MODULE_DEVICE_TABLE(of, env100_i2c_of_match);
static const struct i2c_device_id env100_i2c_id[] = {
{ "env100" },
{ }
};
MODULE_DEVICE_TABLE(i2c, env100_i2c_id);
static struct i2c_driver env100_i2c_driver = {
.driver = {
.name = "env100-i2c",
.of_match_table = env100_i2c_of_match,
},
.probe = env100_i2c_probe,
.id_table = env100_i2c_id,
};
module_i2c_driver(env100_i2c_driver);
MODULE_DESCRIPTION("Acme env100 sensor, I2C interface");
MODULE_LICENSE("GPL");
MODULE_IMPORT_NS(ENV100);In Linux 6.12 the probe callback of an I2C driver takes only the client, since the extra argument that carried the matched i2c_device_id was removed from the interface. The regmap I2C backend chooses the right transaction shape for the configured widths: with 8-bit register addresses and 8-bit values, a read is a write of the register number then a read with a repeated start, the shape most chips expect. The interrupt number comes from client->irq, which the I2C core fills from the node's interrupts property.
The SPI front end
The SPI file differs only in the map creation and in the config, because this chip marks a read by setting bit 7 of the address byte. Regmap supports that with a flag mask, so the shared config is copied and adjusted:
#include <linux/mod_devicetable.h>
#include <linux/module.h>
#include <linux/regmap.h>
#include <linux/spi/spi.h>
#include "env100.h"
static int env100_spi_probe(struct spi_device *spi)
{
struct regmap_config cfg = env100_regmap_config;
struct regmap *map;
cfg.read_flag_mask = 0x80;
spi->mode = SPI_MODE_0;
spi->bits_per_word = 8;
if (spi_setup(spi))
return dev_err_probe(&spi->dev, -EINVAL, "spi_setup failed\n");
map = devm_regmap_init_spi(spi, &cfg);
if (IS_ERR(map))
return dev_err_probe(&spi->dev, PTR_ERR(map),
"regmap init failed\n");
return env100_core_probe(&spi->dev, map, "env100", spi->irq);
}
static const struct of_device_id env100_spi_of_match[] = {
{ .compatible = "acme,env100" },
{ }
};
MODULE_DEVICE_TABLE(of, env100_spi_of_match);
static const struct spi_device_id env100_spi_id[] = {
{ "env100" },
{ }
};
MODULE_DEVICE_TABLE(spi, env100_spi_id);
static struct spi_driver env100_spi_driver = {
.driver = {
.name = "env100-spi",
.of_match_table = env100_spi_of_match,
},
.probe = env100_spi_probe,
.id_table = env100_spi_id,
};
module_spi_driver(env100_spi_driver);
MODULE_DESCRIPTION("Acme env100 sensor, SPI interface");
MODULE_LICENSE("GPL");
MODULE_IMPORT_NS(ENV100);With read_flag_mask = 0x80, a read of register 0xD0 goes on the wire as the byte 0xD0 | 0x80, which is 0xD0 with bit 7 already set, and a write goes out unchanged. The framing lag, the one byte between command and reply, is handled inside regmap, which is the reason to use it: a hand-written SPI driver is where off-by-one errors on received bytes live. Calling spi_setup after setting the mode applies the change and validates it against the controller. The speed comes from spi-max-frequency in the tree, and the core clamps it to what the controller supports.
The core: verifying the chip and reading the temperature
Now the part that knows the chip. The core's probe does what every good probe does: verify the hardware, allocate state, register with a subsystem. Temperature belongs in IIO, the kernel's framework for sensors and converters, because it gives a standard sysfs layout, units and, later, buffered capture. The channel table describes one temperature channel with a raw value and a scale:
struct env100 {
struct device *dev;
struct regmap *map;
};
static const struct iio_chan_spec env100_channels[] = {
{
.type = IIO_TEMP,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
BIT(IIO_CHAN_INFO_SCALE),
},
};
static int env100_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val, int *val2, long mask)
{
struct env100 *env = iio_priv(indio_dev);
__be16 buf;
int ret;
switch (mask) {
case IIO_CHAN_INFO_RAW:
ret = regmap_bulk_read(env->map, ENV100_REG_TEMP, &buf, sizeof(buf));
if (ret)
return ret;
*val = (s16)be16_to_cpu(buf);
return IIO_VAL_INT;
case IIO_CHAN_INFO_SCALE:
/* 1/128 degree per count = 7.8125 millidegrees per count */
*val = 7;
*val2 = 812500;
return IIO_VAL_INT_PLUS_MICRO;
default:
return -EINVAL;
}
}
static const struct iio_info env100_info = {
.read_raw = env100_read_raw,
};Two details are worth slowing down for. The raw value is a signed 16-bit quantity stored big-endian across two consecutive registers, so the code reads both bytes in one bulk transaction, which on I2C is one transfer and on SPI one chip-select assertion, converts with be16_to_cpu and casts to s16 so that negative temperatures stay negative. And the scale is returned as the pair 7 and 812500, with the return code IIO_VAL_INT_PLUS_MICRO, which means the value is 7 + 0.812500, millidegrees per count. IIO's rule is that raw times scale gives the standard unit, and for a temperature the unit is millidegrees Celsius. A raw word of 0x0C80 is 3200 counts, and 3200 times 7.8125 is 25000 millidegrees, 25.0 degrees.
The core's probe verifies the chip, switches it to continuous mode and registers:
int env100_core_probe(struct device *dev, struct regmap *map,
const char *name, int irq)
{
struct iio_dev *indio_dev;
struct env100 *env;
unsigned int id;
int ret;
ret = regmap_read(map, ENV100_REG_ID, &id);
if (ret)
return dev_err_probe(dev, ret, "cannot read id\n");
if (id != ENV100_ID_VALUE)
return dev_err_probe(dev, -ENODEV, "unexpected id 0x%02x\n", id);
indio_dev = devm_iio_device_alloc(dev, sizeof(*env));
if (!indio_dev)
return -ENOMEM;
env = iio_priv(indio_dev);
env->dev = dev;
env->map = map;
ret = regmap_update_bits(map, ENV100_REG_CTRL, ENV100_CTRL_MODE,
FIELD_PREP(ENV100_CTRL_MODE, ENV100_MODE_CONT));
if (ret)
return dev_err_probe(dev, ret, "cannot start conversion\n");
indio_dev->name = name;
indio_dev->info = &env100_info;
indio_dev->modes = INDIO_DIRECT_MODE;
indio_dev->channels = env100_channels;
indio_dev->num_channels = ARRAY_SIZE(env100_channels);
ret = devm_iio_device_register(dev, indio_dev);
if (ret)
return ret;
dev_info(dev, "env100 ready\n");
return 0;
}
EXPORT_SYMBOL_NS_GPL(env100_core_probe, ENV100);The ID check is the line that makes a declared-but-absent device harmless: if nothing answers, the regmap read fails with a bus error and probe returns it, and if something else answers, the mismatch returns -ENODEV. The kernel's I2C and SPI cores never probe for the chip, so only this check keeps a wrong device tree from creating a driver bound to nothing. The symbol is exported in a namespace, ENV100, which the two front ends import with MODULE_IMPORT_NS, so the shared core is not part of the global kernel namespace. Build all three files into one module or as a core module with two front-end modules, with the usual Kconfig symbols ENV100, ENV100_I2C and ENV100_SPI selecting the core.
What the user sees
With the I2C node, the sensor at 25.0 degrees and the three modules loaded:
dmesg | tail -1
cd /sys/bus/iio/devices/iio:device0
ls
cat name in_temp_raw in_temp_scale[ 64.113902] env100-i2c 1-0048: env100 ready
in_temp_raw in_temp_scale name of_node subsystem uevent
env100
3200
7.812500000Raw 3200 times scale 7.8125 is 25000 millidegrees. The same files appear with the SPI node, under a different parent device, and nothing in user space can tell the difference, which is the point of the design. Tools built on libiio, and the in-kernel iio-hwmon bridge that turns an IIO channel into an hwmon temperature for lm-sensors, work without chip-specific code.
Reading registers the hard way, and when to
Regmap handles the transaction shape for you, but not every chip fits. Knowing what lies underneath explains the errors you will see. I2C offers two ways to talk. The SMBus helper functions, such as i2c_smbus_read_byte_data, perform fixed transaction shapes with 8-bit register numbers, and the core emulates them on any adapter that supports general messages. i2c_transfer sends an arbitrary list of messages, with a repeated start between consecutive ones, and is required for 16-bit register addresses, reads longer than 32 bytes, or a stop in the middle of a sequence. SMBus words are low byte first, so a chip that sends the high byte first needs i2c_smbus_read_word_swapped. SPI offers a message made of transfers. A driver builds a struct spi_message, adds struct spi_transfer entries with DMA-safe buffers, and calls spi_sync, or uses spi_write_then_read for the common register-style exchange. Regmap uses exactly these calls on your behalf.
Choose raw transfers when the register model does not fit, such as a display controller that takes a command stream, and choose regmap when it does. Two tests decide it quickly. If every access is "write a register number, then read or write N bytes", regmap fits. If a transaction depends on state between messages, or needs framing that regmap's flags cannot describe, build messages by hand and take care that buffers are not on the stack, since controllers may use DMA.
Interrupts: the alert pin
The alert output tells the host the limit was crossed, so the driver can report it immediately instead of polling. The pin is wired to a GPIO that the device tree names in interrupts, and the core filled client->irq or spi->irq from it. Because reading the status register is a bus transfer that sleeps, the handler must be a threaded one, and because the alert is a level that stays asserted until the chip's status is read, the request needs IRQF_ONESHOT, which keeps the line masked until the thread finishes:
static irqreturn_t env100_alert_thread(int irq, void *data)
{
struct iio_dev *indio_dev = data;
struct env100 *env = iio_priv(indio_dev);
unsigned int status;
int ret;
ret = regmap_read(env->map, ENV100_REG_STATUS, &status);
if (ret) {
dev_err_ratelimited(env->dev, "cannot read status: %d\n", ret);
return IRQ_NONE;
}
if (!(status & ENV100_STATUS_ALERT))
return IRQ_NONE;
iio_push_event(indio_dev,
IIO_UNMOD_EVENT_CODE(IIO_TEMP, 0, IIO_EV_TYPE_THRESH,
IIO_EV_DIR_RISING),
iio_get_time_ns(indio_dev));
return IRQ_HANDLED;
}
static int env100_setup_irq(struct iio_dev *indio_dev, int irq)
{
struct env100 *env = iio_priv(indio_dev);
if (irq <= 0)
return 0; /* no alert wired: polling only */
return devm_request_threaded_irq(env->dev, irq, NULL,
env100_alert_thread, IRQF_ONESHOT,
dev_name(env->dev), indio_dev);
}The NULL hard handler is allowed only with IRQF_ONESHOT. The trigger type comes from the device tree, so the code does not pass trigger flags. Returning IRQ_NONE when the status shows no alert lets the kernel detect a line that fires with no cause, and a failed read is logged at a limited rate so that a broken bus does not flood the log. In probe, call env100_setup_irq after the registration succeeds, and enable the alert in the control register only when an interrupt is wired. The count of serviced interrupts appears in /proc/interrupts under the device name, and a thread named irq/<number>-<name> appears in the process list, where it can be given a real-time priority if latency matters. Level interrupts without the oneshot flag are the classic storm: the line is still asserted when it is unmasked, and the CPU re-enters the handler before the thread has read the status.
When transfers fail
An I2C driver that handles errors well distinguishes three outcomes. A negative return of -ENXIO means the address was NACKed, so nothing answered: wrong address, no power, a held reset line or a busy chip. -EREMOTEIO means a data byte was refused, so the chip answered and the protocol or the chip state is wrong. -ETIMEDOUT means the controller gave up, which is a stuck line or a slow target stretching the clock beyond the adapter's timeout. The core retries a transfer only on arbitration loss, -EAGAIN, and only if the adapter has retries configured, so every other policy belongs to the client.
Retry only what is safe to repeat. A read of the temperature is idempotent, so a bounded retry with a short sleep is reasonable. A command that starts a conversion or clears a flag is not, because a repeat after a lost acknowledgment performs it twice. For a chip that NACKs while busy, such as an EEPROM finishing a write, poll with a bounded loop using time_before and usleep_range, not a fixed msleep, and give up with -ETIMEDOUT. A bus left stuck by a chip that reset mid-byte holds SDA low until nine clock pulses release it, which the core does automatically when the controller supplies recovery information through scl-gpios and sda-gpios. Log every failure once, with the operation, the register and the error name, and rate-limit anything that can repeat.
SPI has fewer failure modes, because without acknowledgment the bus cannot tell you much. Errors are controller-side: a timeout from the controller driver, an unsupported mode rejected by spi_setup, a transfer longer than the controller allows. A chip that is absent or in the wrong mode returns all 0xff or all 0x00, and only a value check in the driver, such as the ID read above, can notice. That is the strongest reason to verify the chip in probe on SPI.
Hwmon or IIO
The same temperature could be exposed through hwmon, the kernel's monitoring interface, which gives temp1_input in millidegrees and standard limit and alarm files that lm-sensors, thermal zones and fan control understand. The rule of thumb is simple. If the value exists to be monitored against limits, as with a CPU or board temperature, hwmon is the idiom, registered with devm_hwmon_device_register_with_info and a struct hwmon_ops whose read, write and is_visible callbacks switch on a sensor type and attribute. If the chip is a general sampler, with several channel types, scales or buffered capture, IIO is the idiom. Many sensors do both: register with IIO, and let the in-kernel iio-hwmon driver, configured with an io-channels property in the device tree, present the channel as an hwmon device. The unit rules apply in both: millidegrees for temperature, never degrees and never a pre-scaled value placed in a raw attribute.
Debugging in layers
When the sensor misbehaves, work from the outside in, because each layer has a tool and each tool removes a category of cause.
Start with the device and the driver. Does /sys/bus/i2c/devices/1-0048 exist, and does it have a driver link? If the device exists with no link, no driver matched: compare the node's compatible string, from the live tree under /proc/device-tree, with the module's aliases from modinfo -F alias. If no device exists, the node is disabled, the wrong blob was booted, or the adapter never registered, which the log under dmesg shows. Then the probe: a message such as cannot read id: -121 is -EREMOTEIO, the chip NACKed.
Then the traffic. The I2C subsystem has tracepoints that record every message, and enabling them is two commands:
echo 1 | sudo tee /sys/kernel/tracing/events/i2c/enable
cat /sys/bus/iio/devices/iio:device0/in_temp_raw
sudo grep i2c_ /sys/kernel/tracing/trace | tail -43200
cat-701 [001] .... 214.510: i2c_write: i2c-1 #0 a=048 f=0000 l=1 [f8]
cat-701 [001] .... 214.510: i2c_read: i2c-1 #1 a=048 f=0001 l=2
cat-701 [001] .... 214.511: i2c_reply: i2c-1 #1 a=048 f=0001 l=2 [0c-80]
cat-701 [001] .... 214.511: i2c_result: i2c-1 n=2 ret=2The four lines show the bulk read of the two temperature registers: write the register number 0xf8, then read two bytes with a repeated start, and the reply 0c 80 is 0x0C80, 3200 counts. The trace proves what the driver asked for and what the adapter reported. It cannot show the waveform, so when the bytes are right and the chip still misbehaves, put a logic analyzer on SDA and SCL, with a sample rate of at least ten times the bus clock, and decode with the I2C protocol decoder. The decoded line should show the same address and bytes, with an acknowledgment after each, and a NACK from the controller after the last byte read. A mismatch between trace and waveform points to the adapter, a level shifter or a mux. SPI has no tracepoints at the message level that match the wire, but the spi trace events show each message and transfer, and a decoder on a logic analyzer shows chip select, clock and both data lines.
Finally, the register state. Regmap publishes /sys/kernel/debug/regmap/<device>/registers, a dump of every register, read from the chip for volatile ones and from the cache for the rest, which shows at a glance whether the control register holds what the driver wrote. Run the first bring-up with cache_type = REGCACHE_NONE so that every read reaches the chip, and enable the cache once behavior is understood. A leak or a race in probe and remove is found by unbinding and rebinding in a loop through the bus's sysfs unbind and bind files.
The layer below: controller drivers
Everything so far used a controller someone else wrote. Writing one shows what the client API really promises. An I2C adapter driver is a platform driver that fills a struct i2c_adapter with an algorithm, struct i2c_algorithm, holding two callbacks: master_xfer, which runs a list of messages and returns the count completed, and functionality, which reports what the adapter supports, usually I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL. It sets the bus speed from the controller's input clock and the clock-frequency property, signals byte completion through an interrupt and a completion with a timeout, maps hardware conditions to -ENXIO, -EAGAIN and -ETIMEDOUT, always sends a stop at the end of a transfer even after an error, and registers with devm_i2c_add_adapter after setting adap.dev.of_node, which is what makes the core create client devices from the child nodes.
An SPI controller driver is simpler because the core takes over message queueing. It allocates with devm_spi_alloc_host, declares its capabilities, which are num_chipselect, mode_bits, bits_per_word_mask and the speed limits, and supplies set_cs, which receives the logic level for the select pin already corrected for SPI_CS_HIGH, and transfer_one, which clocks one buffer and returns 0 when done, a positive value if it will call spi_finalize_current_transfer later, or a negative errno. Because SPI is full duplex, it must always clock out something, with filler when the client gave no transmit buffer. It registers with devm_spi_register_controller. The core's message pump then handles chip select assertion, inter-transfer delays and sequencing for every client on that bus.
Both are platform drivers in the sense of the companion guide, matched by compatible, mapping registers with devm_platform_ioremap_resource, enabling clocks and requesting interrupts with managed calls. Production controllers add FIFOs and DMA, runtime power management that gates the clock between transfers, bus recovery on I2C, and support for features such as 10-bit addressing or quad SPI. The things a client driver can rely on, such as ordered execution of messages, the repeated start between messages of one i2c_transfer, and chip select held across one spi_message, are all guarantees these drivers implement.
Power, supplies and runtime management
A sensor on a battery should not conduct all day. The chip's supply and any reference voltage come from regulators named in the tree, vdd-supply and similar properties, and the driver enables them with devm_regulator_get_enable before the first bus access. The chip's own sleep mode, bits 1:0 of the control register, is the cheaper way to save power, and runtime power management ties it to use: bracket each read with pm_runtime_resume_and_get and pm_runtime_put_autosuspend, write runtime_resume to set continuous mode and runtime_suspend to set sleep, set an autosuspend delay of a few hundred milliseconds so bursts of reads do not cycle the chip, and enable it in probe with pm_runtime_set_active and devm_pm_runtime_enable. The device's power directory in sysfs then shows runtime_status, and control can pin it on for debugging. Remember that a chip returning to continuous mode needs its conversion time before the first sample is valid, which the datasheet states, so the resume callback waits that long or the driver reports the first read as stale.
Testing without the board
Not every check needs hardware. Property parsing and conversion logic are pure functions that you can test by compiling them in a user-space harness with a few test vectors: raw 0xFF80 should convert to minus 1000 millidegrees, 0x0C80 to 25000, and 0x8000 to the chip's minimum. Put those cases in comments beside the conversion so the next reader sees the arithmetic. The kernel's i2c-stub module simulates an I2C chip that you preload with register values, which exercises the client driver's transfers on any machine, and spi-loopback-test checks controllers. Boot a test kernel with CONFIG_KASAN and CONFIG_PROVE_LOCKING and run unbind and bind cycles, which finds memory errors and lock misuse that never appear on a bench. And always run make dtbs_check against the binding for the chip, so that a board file with a misspelled property fails in the build, not in the field.
Several chips on one bus
A product rarely has one sensor. Two chips with the same fixed I2C address cannot share a bus, and the usual remedies are a chip variant with a pin that selects an alternate address, which our env100 has with its two addresses 0x48 and 0x49, a second adapter, or an I2C multiplexer. A multiplexer such as the common PCA954x family appears in the device tree as a node under the controller with children for each downstream channel, and the kernel's mux core creates a new adapter for each one, so a client under channel 2 is a client of a new bus number. The driver for the chip does not change at all, which is the reward for keeping the bus behind the core.
Shared buses also share their speed. The bus runs at one frequency, set by the controller node's clock-frequency, and every device on it must tolerate it. If one chip supports only 100 kHz and the others support 400 kHz, the bus runs at 100 kHz, or the slow chip moves to its own adapter. The same is true electrically: each device adds capacitance, and the pull-up resistors must pull the lines high within the rise time the speed requires, which is why a bus that works with two devices can fail with six.
SPI gets its sharing from chip selects. Each device has its own select line, and the controller's num_chipselect bounds how many. When the controller runs out, boards use GPIOs as selects, declared with cs-gpios in the controller node, and the core drives them itself. Different devices on one SPI bus may need different modes and speeds, and the core applies each device's settings before every message, which is why a client sets its own mode with spi_setup in probe and not on the shared controller.
Choosing the bus speed
Speed is the one setting that is both a performance and a reliability decision. For I2C, pick the highest standard mode that every device on the bus supports and that the wiring can carry: 100 kHz for long runs and many devices, 400 kHz for ordinary board-level buses. A temperature sensor read once a second gains nothing from 400 kHz and risks a marginal bus, so the conservative choice is correct until a measurement says otherwise. Put the speed in the device tree, since it is a property of the board and not of the driver.
For SPI, the datasheet gives a maximum clock for the chip, and the board's trace length and signal quality may lower it. The device tree property spi-max-frequency records that limit for each device, and the core passes the smaller of it and the controller's capability to the controller driver as the transfer's speed_hz. A driver should never hard-code a speed above what the node says, and should treat the node value as authoritative. When a chip works at 1 MHz and fails at 5 MHz, the usual causes are signal integrity and setup time, not the protocol, and a scope on the clock and data lines shows the edge quality directly. The counterpart on I2C is the rise time of SDA and SCL, which the pull-up value controls.
A pre-ship checklist for bus drivers
Before a bus driver leaves the bench, check the items that cause most field failures. Does probe verify an ID or a known register value, so a wrong device or a missing one fails cleanly? Does every transfer path return the bus error to the caller, with a log line that names the operation and the code? Are all buffers handed to SPI transfers DMA-safe, in driver data with proper alignment? Is every non-idempotent command protected from blind retries? Does the driver work with no interrupt wired, by polling? Does the device suspend when idle and resume correctly, including the settling time after wake? Does the module autoload, with MODULE_DEVICE_TABLE entries for the device tree, the ACPI IDs and the bus ID table? Does make dtbs_check pass against a written binding? And do repeated unbind and bind cycles run quietly under kmemleak? Each of these has turned up as a real bug in a shipped kernel driver, and checking them takes less time than diagnosing one from a customer log.
Boundaries and traps
Three kinds of reader should treat this guide as a starting point. If you control a high-rate converter, with samples every few microseconds, a bus driver in process context is not enough: look at IIO triggered buffers, DMA-capable SPI controllers and, for the extreme cases, a dedicated microcontroller. If the chip is on a bus that is neither I2C nor SPI, such as I3C, UART, CAN or a one-wire protocol, the structure of a core plus front ends still applies but the subsystems differ. And if you only need the data once, a user-space tool with i2c-dev or spidev is quicker than a driver.
A few traps recur. Addresses in datasheets are sometimes eight-bit with the read/write bit, and Linux uses seven: shift right by one. Buffers handed to SPI transfers must be DMA-safe, never on the stack. Byte order in registers is the chip's choice, not the bus's. A scale that is not documented to produce millidegrees is a bug in the driver, not a feature. And driver APIs move between releases: this guide uses the Linux 6.12 forms, where I2C and SPI probe take only the device and the SPI controller allocator is devm_spi_alloc_host, so check the headers of the kernel you build against before copying a line.


