Skip to content
systemcoding.dev
Kernels

Access SPI Devices From User Space With spidev

Expose an SPI device as /dev/spidevB.C, set mode, speed and word size with ioctl, and run full-duplex transfers with SPI_IOC_MESSAGE in a small C program.

6 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Linux, Arm and C logos.

Bringing up an SPI chip is the same story as for I2C: before you write a kernel driver, prove the wiring and the protocol from user space. Linux offers the spidev driver for that. It exposes an SPI device as a character node, /dev/spidev0.0, and lets a program set the clock mode and speed and exchange bytes with the chip. This post covers what must be in place for the node to exist, a first full-duplex transfer in C using ioctl, how to read a typical chip ID, and the pitfalls that produce all-zero or all-ones replies. It uses Linux 6.12 and GCC 14. The kernel's spidev documentation is the primary source. Results are computed from the code and are not from a particular board; any ID value comes from an imaginary flash chip.

What has to exist first

spidev is a driver bound to an SPI device, so the device tree must contain an SPI child node and the driver must claim it. For a long time the idiom was compatible = "spidev", but that string is rejected by recent kernels, which log a warning such as buggy DT: spidev listed directly in DT and refuse to treat it as a hardware description. The accepted route is to use the compatible string of a real chip that the spidev driver knows, from its of_device_id list in drivers/spi/spidev.c, for example "rohm,dh2228fv", or to bind by driver_override at run time. Raspberry Pi kernels carry patches that keep the old behavior for their overlays, so on a Pi the standard dtparam=spi=on just works.

On a generic board, a node looks like this:

spidev-node.dtsdts
&spi0 {
    status = "okay";

    flash@0 {
        compatible = "rohm,dh2228fv";
        reg = <0>;
        spi-max-frequency = <1000000>;
    };
};

The kernel must also include CONFIG_SPI_SPIDEV. Check the result in /dev:

Shell
ls -l /dev/spidev*
Text
crw-rw---- 1 root spi 153, 0 Nov 23 10:12 /dev/spidev0.0

The name is spidev<bus>.<chip select>. Major number 153 is reserved for SPI. If the node is missing, no driver bound, which is the thing to check in /sys/bus/spi/devices.

The ioctl interface

User space configures the device and transfers through the calls defined in <linux/spi/spidev.h>:

ioctlPurpose
SPI_IOC_WR_MODE / SPI_IOC_RD_MODESet or read the SPI mode, 0 to 3, as a uint8_t
SPI_IOC_WR_BITS_PER_WORDBits per word, normally 8
SPI_IOC_WR_MAX_SPEED_HZClock speed in hertz as a uint32_t
SPI_IOC_WR_LSB_FIRSTBit order
SPI_IOC_MESSAGE(N)Run N transfers as one chip-select assertion

Plain read and write also work, but they are half duplex and cannot control chip select between transfers, so SPI_IOC_MESSAGE is the real interface.

A full-duplex transfer

An SPI transfer clocks bits out and in simultaneously. struct spi_ioc_transfer describes one transfer with a transmit buffer, a receive buffer and a length, and both buffers are the same length because the same number of clocks drives both directions. To read a chip, you send the command byte followed by dummy bytes, and the answer arrives in the receive buffer during the dummy bytes.

This program reads the three-byte JEDEC ID of a flash chip, using the standard command 0x9F:

spi_id.cc
#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)
{
    const char *dev = "/dev/spidev0.0";
    uint8_t mode = SPI_MODE_0;
    uint8_t bits = 8;
    uint32_t speed = 1000000;
    uint8_t tx[4] = { 0x9F, 0x00, 0x00, 0x00 };
    uint8_t rx[4] = { 0 };
    struct spi_ioc_transfer xfer;
    int fd = open(dev, O_RDWR);

    if (fd < 0) {
        perror(dev);
        return 1;
    }
    if (ioctl(fd, SPI_IOC_WR_MODE, &mode) < 0 ||
        ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits) < 0 ||
        ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed) < 0) {
        perror("configure");
        return 1;
    }

    memset(&xfer, 0, sizeof(xfer));
    xfer.tx_buf = (unsigned long)tx;
    xfer.rx_buf = (unsigned long)rx;
    xfer.len = sizeof(tx);
    xfer.speed_hz = speed;
    xfer.bits_per_word = bits;

    if (ioctl(fd, SPI_IOC_MESSAGE(1), &xfer) < 0) {
        perror("SPI_IOC_MESSAGE");
        return 1;
    }
    printf("manufacturer=0x%02x type=0x%02x capacity=0x%02x\n",
           rx[1], rx[2], rx[3]);
    close(fd);
    return 0;
}

Compile with gcc -Wall -o spi_id spi_id.c and run it. For a Winbond W25Q32 flash, whose datasheet gives the ID bytes EF 40 16, the output would be:

Text
manufacturer=0xef type=0x40 capacity=0x16

The first received byte, rx[0], arrives while the command goes out and carries no useful data, so the program prints from index 1. That off-by-one is the most common mistake in first SPI programs: the reply to a command is always delayed by the command's own byte count. The clock edges that fetched rx[1] through rx[3] were produced by the three dummy zero bytes in tx.

Several transfers in one transaction

Some devices need a command, a pause or a changed speed, then a data phase, all within one chip-select assertion. Pass an array of transfers to SPI_IOC_MESSAGE(N). The chip select stays low across them, unless a transfer sets cs_change:

spi_two_xfers.cc
struct spi_ioc_transfer xfers[2];

memset(xfers, 0, sizeof(xfers));
xfers[0].tx_buf = (unsigned long)cmd;
xfers[0].len = 4;                 /* read command and 3-byte address */
xfers[1].rx_buf = (unsigned long)data;
xfers[1].len = 256;               /* then clock in 256 bytes */

ioctl(fd, SPI_IOC_MESSAGE(2), xfers);

The first transfer sends the command and receives nothing meaningful; the second sends nothing and keeps the clock running to read 256 bytes. Because the pair is submitted together, the kernel runs them back to back without releasing the chip select, which is how flash read commands are built.

Choosing the mode

The mode comes from the chip's datasheet. For most devices, the timing diagram shows the clock idle level and the edge on which data is sampled:

ModeCPOLCPHAClock idlesData sampled on
000LowRising edge
101LowFalling edge
210HighFalling edge
311HighRising edge

Most flash and many sensors work in mode 0 or 3. If your first read returns all 0xFF or 0x00, suspect the wiring first, then the mode. Try each of the four while watching a logic analyzer, or the output of an echo test, described below.

A loopback test

To separate wiring from chip problems, connect MOSI to MISO with a jumper wire, with no device attached. Then whatever you send comes back. The kernel ships a test program, tools/spi/spidev_test.c, and the invocation looks like this:

Shell
./spidev_test -D /dev/spidev0.0 -s 500000 -p "hello"
Text
spi mode: 0x0
bits per word: 8
max speed: 500000 Hz (500 KHz)
TX | 68 65 6C 6C 6F  | hello
RX | 68 65 6C 6C 6F  | hello

If the received bytes match, the controller and the wiring on its side work. If they are zeros, the controller is not driving MOSI, or the jumper is on the wrong pin. Use it before blaming the chip.

Common problems

  • **No /dev/spidev*.** The module is not built, SPI is not enabled in the configuration, or no device node is bound to spidev.

  • **Device or resource busy.** A kernel driver already owns the chip select, for example an MTD flash driver. Only one driver can bind a given device.

  • **All 0xFF.** The chip is not driving MISO. Check power, chip select polarity, reset pins and the mode.

  • Wrong chip select. Two devices on spidev0.0 and spidev0.1 need separate nodes and separate select lines.

  • Speed too high. The controller clamps the speed to what its clock divider supports, and the chip may not keep up at that speed. Start at 1 MHz.

Boundaries

spidev is a tool for bring-up, prototypes and low-rate control. It has no interrupt delivery, the timing of a user-space loop is not deterministic, and every transfer pays a system call. Production designs use a kernel driver that plugs into a subsystem, such as IIO for converters or MTD for flash, which later posts in this cluster build.

Also inEmbedded
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.