Module 22 · Lesson 27 of 64

SPI transfers with spidev

Configure SPI mode and clock, run full-duplex transfers from Python with spidev, and verify a transaction with a loopback wire or a real device.

  • Beginner to advanced
  • 10 min read
  • 35 min lab
What you will need

Ubuntu 24.04 on a Raspberry Pi 4 or 5 with SPI enabled; python3-spidev (or pip in a venv); a jumper wire for loopback; optional MCP3008, potentiometer and logic analyzer; Ubuntu in WSL2 or a VM is enough for the warm-up exercise

Your place in the module
By the end you can 4 objectives
  • Enable SPI on the Pi and identify the /dev/spidevX.Y node for a given bus and chip select
  • Set the CPOL/CPHA mode and max_speed_hz to match a device datasheet
  • Run full-duplex transfers with xfer2 and one-directional reads and writes with readbytes and writebytes
  • Verify a transfer with a MOSI-to-MISO loopback or a logic analyzer capture
Video coming soonSPI transfers with spidev
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from I2C sensors with smbus2
  • I2C is a two-wire open-drain bus where every device answers a 7-bit address, and most sensors are a register map read through SMBus-style transactions.
  • smbus2's read_i2c_block_data and write_i2c_block_data move blocks of bytes, and byte order is your responsibility, not the library's.
  • Reading an address with no device behind it raises OSError with errno 121 (Remote I/O error), which is how a scan detects presence.
01

Four wires and a mode number

4 min read

In the previous lesson you decoded sensor registers over I2C. This lesson uses the faster SPI bus, sets CPOL/CPHA modes and runs full-duplex transfers with spidev.

SPI connects one master (the Pi) to one or more devices with four signals. carries what you send. carries what you receive. SCLK is the clock, always driven by the master. CS (chip select) is an active-low line that tells one specific device to listen. Where I2C put an address byte on the wire, SPI uses a wire per device: the selected device has its CS pulled low, and every other device ignores the clock and the data. That is why SPI needs no addressing scheme and no arbitration, and why it can run at tens of megahertz where I2C usually runs at 100 or 400 kHz.

The key property is . Inside the master and the device, the MOSI and MISO lines connect two shift registers. Each clock edge shifts one bit out on MOSI and samples one bit in from MISO. A transfer of N bytes therefore always clocks N bytes out and N bytes in, even when one direction is meaningless. The practical consequence: to read anything, you must write something. A device only outputs data while the master supplies clock edges, so reads are done by sending dummy bytes and keeping what comes back.

The two sides must also agree on the clock format. and combine into four SPI modes, numbered 0 to 3, with mode = (CPOL << 1) | CPHA. The device datasheet states the mode, either as a number or as a timing diagram you decode yourself.

The four SPI modesMode 000lowrising (1st)Mode 101lowfalling (2nd)Mode 210highfalling (1st)Mode 311highrising (2nd)columns: CPOL, CPHA, idle level, sampling edge
The four SPI modes: CPOL sets the idle clock level, CPHA picks the sampling edge.

Getting the mode wrong rarely gives you an error. It gives you data sampled one edge too early or too late: values that look plausible but are bit-shifted or stuck at zero. If a sensor returns garbage, the mode is the first thing to check against the datasheet.

The clock speed is the other agreement. You request an upper bound in hertz, and the SPI controller derives SCLK by dividing its source clock, so only certain speeds are actually possible. The driver picks the fastest achievable speed that does not exceed your request. The speed you actually get is only visible on a logic analyzer, because spi.max_speed_hz just returns the limit you stored. Treat your setting as a ceiling, and stay under the device's datasheet limit, which often depends on its supply voltage.

On the Pi, SPI is exposed through character devices named /dev/spidevX.Y, where X is the bus (controller) number and Y is the chip select on that bus. Enable the main controller by making sure dtparam=spi=on is present in /boot/firmware/config.txt (the boot configuration file on Ubuntu 24.04 images for the Pi), then reboot. After that:

bash
ls /dev/spidev*

On a Pi 4 or 5 with SPI0 enabled this lists /dev/spidev0.0 and /dev/spidev0.1, one node per chip select. The exact names on your machine depend on which controllers and chip selects your board exposes. SPI0 sits on the 40-pin header: GPIO10 is MOSI (physical pin 19), GPIO9 is MISO (pin 21), GPIO11 is SCLK (pin 23), GPIO8 is CE0 (pin 24) and GPIO7 is CE1 (pin 26). The kernel drives these pins for you while a transfer runs; you do not toggle them from Python.

02

Full-duplex transfers with spidev

4 min read

Install the module with sudo apt install python3-spidev, or pip install spidev inside your project's virtual environment. The import name is spidev and the class is SpiDev. The whole setup is four lines:

python
import spidev

spi = spidev.SpiDev()
spi.open(0, 0)               # /dev/spidev0.0: bus 0, chip select 0
spi.mode = 0                 # CPOL=0, CPHA=0
spi.max_speed_hz = 1_000_000

bits_per_word defaults to 8 and lsbfirst defaults to False (most significant bit first), which is what almost every datasheet expects, so you rarely touch them. Set mode and max_speed_hz before the first transfer.

The workhorse method is xfer2. It takes a list of integers from 0 to 255, clocks them out on MOSI while chip select stays low for the whole buffer, and returns a list of the same length: the bytes that arrived on MISO during those same clock edges. The simplest way to see full duplex working needs no device at all: connect GPIO10 (MOSI, pin 19) to GPIO9 (MISO, pin 21) with one jumper wire. Everything the Pi sends comes straight back.

python
import spidev

spi = spidev.SpiDev()
spi.open(0, 0)
spi.mode = 0
spi.max_speed_hz = 1_000_000
try:
    tx = [0xA5, 0x5A, 0x00, 0xFF]
    rx = spi.xfer2(tx)
    print("sent:", [hex(b) for b in tx])
    print("got: ", [hex(b) for b in rx])
    assert rx == tx, "loopback mismatch: check the MOSI-MISO jumper"
finally:
    spi.close()

If the received list equals the sent list for patterns like 0x00, 0xFF and alternating bits, your mode, clock and wiring are working end to end. Remove the jumper before connecting a real device, or the device's MISO output will fight the MOSI line.

Two convenience methods cover one-directional traffic. spi.readbytes(n) reads n bytes while sending zeros on MOSI, and spi.writebytes(data) sends data and discards whatever arrives. On the wire both are still full-duplex transfers: the clock runs, both lines carry bits, the module just hides the direction you do not care about. Use them when a device datasheet describes a pure read or a pure write; use xfer2 when a command and its response share one chip-select window, which is the common case.

A concrete example: the MCP3008, a 10-bit analog-to-digital converter with 8 input channels, speaks SPI mode 0. One conversion is a single 3-byte transfer, and it shows why full duplex matters.

Step by stepOne MCP3008 conversion in three bytes
  1. Send 0x01: the start bit. The ADC has not decoded a command yet, so the byte you receive is meaningless.

  2. Send 0x80: single-ended mode, channel 0 (the high nibble is 8 plus the channel number). The ADC starts sampling and begins shifting out the result.

  3. Send 0x00: a dummy byte. Its only job is to provide 8 more clock edges so the rest of the sample can arrive.

  4. Combine: the 10-bit value is ((rx[1] & 0x03) << 8) | rx[2], a number from 0 to 1023.

python
rx = spi.xfer2([0x01, 0x80, 0x00])
value = ((rx[1] & 0x03) << 8) | rx[2]
print(f"channel 0: {value} of 1023")
One MCP3008 conversionPi (master)MCP30080x01junk0x80junk + top bits0x0010-bit sample1. Pi (master) → MCP30080x012. MCP3008 → Pi (master)junk3. Pi (master) → MCP30080x804. MCP3008 → Pi (master)junk + top bits5. Pi (master) → MCP30080x006. MCP3008 → Pi (master)10-bit sample
The three-byte MCP3008 transfer: junk comes back while the command goes out, and the sample arrives during the last two bytes.
Power the MCP3008 at 3.3 V

Run the MCP3008's VDD and VREF from the Pi's 3.3 V rail. The Pi's GPIO inputs are not 5 V tolerant, and a 5 V-powered ADC would drive MISO to 5 V. The datasheet's maximum clock also drops at lower supply voltages, so 1 MHz is a safe choice at 3.3 V.

By default /dev/spidev0.0 is owned by root, so a first test may need sudo. Granting your own user access with a group and a udev rule, instead of running hardware scripts as root, is exactly what the next lesson covers.

03

Inside spidev: chip select and buffers

4 min read
Going deeperExplore the mechanism

The spidev module is a C extension. Each transfer method fills in one or more struct spi_ioc_transfer messages (defined in <linux/spi/spidev.h>) and issues an ioctl(fd, SPI_IOC_MESSAGE(n), ...) call. Each transfer carries a transmit buffer pointer, a receive buffer pointer, a length, an optional per-transfer speed and a cs_change flag; chip select stays asserted for the whole SPI_IOC_MESSAGE and rises when the message ends. The mode and speed you set as properties are separate, smaller ioctls (SPI_IOC_WR_MODE, SPI_IOC_WR_MAX_SPEED_HZ) that configure the device before any data moves.

The three transfer methods differ in how they cut the buffer into ioctl calls (checked against the py-spidev source, spidev_module.c):

  • xfer is documented as releasing chip select between blocks (its docstring says "CS will be released and reactivated between blocks"). In the default build of the module it sends the whole list as one transfer, exactly like xfer2, and never sets cs_change. Do not rely on a CS pulse between bytes: if a device needs one, confirm it on a logic analyzer.
  • xfer2 sends the whole list as one transfer in one ioctl, so chip select is asserted for the whole buffer and released only at the end. This is what "one transaction" means for nearly every SPI device: command bytes and response bytes inside one continuous CS-low window. If you tried to build the MCP3008 read from a writebytes followed by a readbytes, they would be two ioctl calls, CS would rise between them and the ADC would abort the conversion. That is the trap xfer2 exists to avoid. The kernel spidev driver copies each message through an internal buffer whose size is the bufsiz module parameter, 4096 bytes by default, so xfer2 cannot send more than that.
  • xfer3 accepts a list of any length by sending it in chunks of at most bufsiz bytes (it reads /sys/module/spidev/parameters/bufsiz). Each chunk is its own ioctl call, so chip select rises between chunks even though the docstring says it is held. For a buffer above 4096 bytes that must be one CS-low window, drive chip select yourself with no_cs (below).

readbytes and writebytes are the same ioctl with one buffer pointer left empty: with no transmit buffer the kernel sends zeros, and with no receive buffer the incoming bytes are discarded. The wire activity is identical to a full-duplex transfer either way.

xfer, xfer2 and xfer3xferxfer2xfer3Chip selectheld low percallheld low percallrises betweenchunksLength limit4096 default4096 defaultany (chunked)Typical usesame as xfer2in practicemost devicesbuffers over4096 bytes
xfer, xfer2 and xfer3 differ only in chip-select handling and buffer length.
Default to xfer2

Use xfer2 for every transaction of at most 4096 bytes. Reach for xfer3 only for longer buffers, knowing chip select rises between its chunks, and for readbytes and writebytes only for genuinely one-directional steps.

There is one more chip-select arrangement worth knowing. By default the SPI controller drives the CE pin itself, one hardware chip select per device node. Setting spi.no_cs = True (the SPI_NO_CS flag) tells the controller to leave chip select alone, and you drive it yourself as an ordinary GPIO, using gpiod from the earlier GPIO lesson: request the line as an output, set it low, run one or more xfer2 calls, then set it high. Use a free GPIO for it, not CE0 or CE1 themselves, which the SPI driver keeps for its own chip selects. Two situations call for this: a protocol that must keep CS low across several separate transfers (some displays and radios do), and a board with more devices than the controller has CE lines, where you wire each device's CS to a free GPIO. The cost is that framing is now your responsibility: exactly one device selected at a time, and CS low before the first clock edge and high only after the last. A logic analyzer on SCLK and CS is the honest way to confirm it, and the practice exercises have you do exactly that.

Everything so far assumed the transfer itself is fast enough and your process has permission to open the node. The next lesson, "Timing limits, permissions and safe hardware practice", answers what happens when those assumptions break: how fast Python can really poll a device, how udev rules open /dev/spidev* to your user without sudo, and how to wire and probe a board so a mistake costs a jumper wire, not a Pi.

Key takeaways

  • SPI moves one bit in each direction on every clock edge, so every transfer of N bytes sends N bytes and receives N bytes
  • The SPI mode number encodes CPOL and CPHA: mode = (CPOL << 1) | CPHA, and it must match the device datasheet
  • xfer2 sends the whole buffer as one SPI message, so chip select stays low for the whole buffer; separate calls are separate messages and chip select rises between them
  • max_speed_hz is an upper bound: the controller divides its source clock, so the effective speed can be lower
Reflect
  1. Explain to a colleague, in two sentences: enable SPI on the Pi and identify the /dev/spidevX.Y node for a given bus and chip select
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. 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

Find your next step

↑ ↓ to move · Enter to open · Esc to close