Raspberry Pi SPI Tutorial (Pi 5): spidev in Python and C++

In this tutorial, we’ll discuss Raspberry Pi SPI on the Raspberry Pi 5: how to enable SPI, the SPI pins and buses, and how to talk to an SPI device with spidev in Python and C++. You’ll learn how to enable SPI three ways (raspi-config, the command line, and config.txt), wire an SPI device, run a loopback test, read and write the registers of a BMP280 sensor over SPI in Python (spidev) and C++ (Linux spidev ioctl), and pick the SPI mode, clock speed, and chip select.

We’ll answer the question: what’s different about SPI on the Raspberry Pi 5 compared to the Raspberry Pi 4 and older boards? You’ll see the Pi 5’s SPI controllers and pins read from my board, my oscilloscope captures of decoded SPI transfers in all four SPI modes, the clock you get for every max_speed_hz value with the rule behind it, the fastest error-free loopback speed, throughput in Python and C++, and the error messages you’ll meet along the way. Without further ado, let’s get right into it!

Note: All examples in this tutorial are tested with: Raspberry Pi 5 (8GB) with Raspberry Pi OS (64-bit) Trixie, and a BMP280 SPI/I2C module.

This tutorial assumes your Raspberry Pi is set up with Raspberry Pi OS and reachable over SSH. If it isn’t, follow the Raspberry Pi Setup Guide first. Every command below runs in an SSH session; my Raspberry Pi SSH tutorial shows how to connect from Windows, macOS, and Linux.

Raspberry Pi SPI (Raspberry Pi 5)

To use SPI on a Raspberry Pi, enable it with sudo raspi-config nonint do_spi 0 (or the dtparam=spi=on line in /boot/firmware/config.txt), connect your device’s MOSI to GPIO10 (pin 19), MISO to GPIO9 (pin 21), SCLK to GPIO11 (pin 23), and CS to CE0, GPIO8 (pin 24), and open /dev/spidev0.0. Then send and receive bytes:

Python Code example (Raspberry Pi SPI read with spidev)

C++ Code example (Raspberry Pi SPI read with the Linux spidev ioctl)

Both read register 0xD0 (the chip ID) of a BMP280 sensor and print Chip ID: 0x58 on my Raspberry Pi 5. Build the C++ one with g++ -std=c++17 quick_spi.cpp -o quick_spi. Neither needs sudo, because the default user is in the spi group, and the Python module ( python3-spidev) is already installed on Raspberry Pi OS. The rest of this tutorial explains each step, the Pi 5 SPI buses, complete examples in both languages, and what the bus looks like on my oscilloscope.

Raspberry Pi SPI quick test: Python spidev and C++ ioctl both read the BMP280 chip ID 0x58 over /dev/spidev0.0
Raspberry Pi SPI quick test: Python spidev and C++ ioctl both read the BMP280 chip ID 0x58 over /dev/spidev0.0


Raspberry Pi SPI Explained

SPI (Serial Peripheral Interface) is a synchronous serial bus with four signals. The Raspberry Pi is the controller (the older name is master): it drives the clock, SCLK, and sends data on MOSI (controller out, peripheral in). Each device sends data back on MISO (controller in, peripheral out). A fourth line, CS (chip select, also called CE or SS), selects one device: it’s active LOW, and only the device whose CS is LOW listens to the clock and drives MISO.

SCLK, MOSI, and MISO are shared by every device on the bus; each device gets its own CS line. SPI has no addresses, no acknowledge bit, and no pull-up resistors: the controller drives the lines push-pull, which is why SPI runs at tens of MHz while I2C stays at a few hundred kHz.

Raspberry Pi SPI bus diagram: Raspberry Pi 5 SPI0 controller with shared SCLK, MOSI and MISO lines and one chip select (CE0, CE1 or a GPIO) per device

SPI is full duplex: every clock pulse moves one bit out on MOSI and one bit in on MISO at the same time. To read a register, you therefore send bytes too: the first byte tells the device which register you want, and while you clock out a dummy byte, the device shifts its answer back. That’s why every SPI read below sends two bytes and gets two bytes back, and why the first received byte is junk.

Tip: I2C vs SPI on the Raspberry Pi: I2C uses two wires and an address per device (up to 112 on one bus, 100kHz by default), and the device acknowledges every byte. SPI needs three shared wires plus one CS per device, has no acknowledge, and runs far faster: up to 50MHz with zero errors on my Raspberry Pi 5. Use I2C for many slow sensors on few pins, and SPI for displays, ADCs, flash memory, and anything that moves a lot of data. The I2C side is covered in my Raspberry Pi I2C tutorial.


Raspberry Pi 5 SPI Pins and Buses

The SPI bus for your devices is SPI0 on GPIO7 to GPIO11, with two chip selects. Linux creates one device file per chip select: /dev/spidev0.0 for CE0 and /dev/spidev0.1 for CE1. These are the same pins as on every Raspberry Pi with a 40-pin header, so older wiring diagrams still apply. The positions on the header are in my Raspberry Pi 5 pinout guide.

Header PinGPIOSPI0 FunctionLinux Device
Pin 19GPIO10MOSI–
Pin 21GPIO9MISO–
Pin 23GPIO11SCLK–
Pin 24GPIO8CE0 (chip select 0)/dev/spidev0.0
Pin 26GPIO7CE1 (chip select 1)/dev/spidev0.1
Pin 1 / 17–3.3vPower for 3.3v SPI modules
Pin 6, 9, 20, 25, …–GNDCommon ground

Note: The Raspberry Pi GPIO pins are 3.3v only and aren’t 5v tolerant. A 5v SPI device drives MISO to 5v and can damage the Raspberry Pi. Use a 3.3v module, or a level shifter on MISO (and on the other lines if the device needs 5v logic levels).

Which SPI Controllers Does the Raspberry Pi 5 Have?

On the Raspberry Pi 5, the SPI controllers live in the RP1 I/O chip. They are Synopsys DesignWare SPI cores ( snps,dw-apb-ssi) driven by the spi_dw kernel driver, not the spi-bcm2835 driver of the Raspberry Pi 4 and older. The device tree on my board lists six of them ( spi0 to spi5 at RP1 addresses spi@50000 to spi@64000), plus a seventh, spi10, that belongs to the BCM2712 itself and isn’t on the header ( config.txt disables it with dtoverlay=nospi10). With SPI enabled, this is what my Pi 5 shows:

Raspberry Pi 5 SPI enabled: /dev/spidev0.0 and /dev/spidev0.1 in the spi group, spi_dw and spidev modules, pinctrl shows GPIO9-11 as SPI0 and GPIO7/GPIO8 as outputs
Raspberry Pi 5 SPI enabled: /dev/spidev0.0 and /dev/spidev0.1 in the spi group, spi_dw and spidev modules, pinctrl shows GPIO9-11 as SPI0 and GPIO7/GPIO8 as outputs

Note the last command: GPIO9, GPIO10, and GPIO11 switch to their SPI0 functions, but GPIO7 and GPIO8 become plain outputs. On the Raspberry Pi 5, the chip selects are GPIO-driven: the driver sets CE0 and CE1 LOW and HIGH itself (the device tree lists them in cs-gpios). That’s what lets you put a chip select on almost any free GPIO, and it’s also why the time from CS falling to the first clock is longer than you might expect (measured further down). The extra controllers are routed to the header with overlays from the overlay README; these are the pins my board’s pinctrl funcs reports for each:

Overlay (Pi 5)SCLKMOSIMISOChip SelectsConflicts
dtparam=spi=onGPIO11GPIO10GPIO9GPIO8, GPIO7–
spi1-1cs / -2cs / -3csGPIO21GPIO20GPIO19GPIO18, GPIO17, GPIO16I2S / PCM pins
spi2-1cs-pi5 / -2cs-pi5GPIO3GPIO2GPIO1GPIO0, GPIO24I2C1 and the HAT EEPROM pins
spi3-1cs-pi5 / -2cs-pi5GPIO7GPIO6GPIO5GPIO4, GPIO25SCLK is SPI0’s CE1
spi5-1cs / -2csGPIO15GPIO14GPIO13GPIO12, GPIO26UART0 TX/RX (GPIO14/15)

SPI1 is the useful second bus: it doesn’t collide with I2C, SPI0, or the serial console. I tested it on my Raspberry Pi 5 with a runtime overlay, which needs no reboot:

Raspberry Pi 5 second SPI bus: sudo dtoverlay spi1-1cs creates /dev/spidev1.0 on GPIO19-21 with GPIO18 as chip select, removed with dtoverlay -r
Raspberry Pi 5 second SPI bus: sudo dtoverlay spi1-1cs creates /dev/spidev1.0 on GPIO19-21 with GPIO18 as chip select, removed with dtoverlay -r

Add dtoverlay=spi1-1cs (or spi1-2cs, spi1-3cs) to config.txt to make it permanent. Be careful with spi3-1cs-pi5: its SCLK is GPIO7, which is SPI0’s CE1. Loading it gives no error at all, yet it takes GPIO7 away from SPI0, and removing the overlay leaves GPIO7 in its SPI3 function, so /dev/spidev0.1 stops selecting anything until you reload SPI or reboot:

Raspberry Pi 5 spi3-1cs-pi5 overlay takes GPIO7 (SPI0 CE1) as SPI3_SCLK without an error and leaves it there after dtoverlay -r
Raspberry Pi 5 spi3-1cs-pi5 overlay takes GPIO7 (SPI0 CE1) as SPI3_SCLK without an error and leaves it there after dtoverlay -r

I restored CE1 by turning SPI off and on again with raspi-config nonint do_spi 1 and do_spi 0. On the Raspberry Pi 4, the extra buses are numbered differently (SPI3 to SPI6 on the BCM2711, with overlays such as spi4-1cs), per the overlay README and pinout.xyz, so don’t copy Raspberry Pi 4 bus maps to a Pi 5.

How to Add More SPI Chip Selects

Because the chip selects are GPIOs, you can move them or add more with overlay parameters. dtoverlay=spi0-2cs,cs0_pin=5,cs1_pin=6 moves SPI0’s two chip selects to GPIO5 and GPIO6, spi0-1cs frees GPIO7 when one device is enough, and spi1-3cs gives three chip selects on SPI1, per the overlay README. A pin that’s already in use can’t be a chip select: SPI0 owns GPIO7 and GPIO8 while SPI is on, so GPIO tools get “Device or resource busy” (the troubleshooting section shows it).


How to Enable SPI on Raspberry Pi

SPI is disabled on a fresh Raspberry Pi OS image: /dev/spidev0.0 doesn’t exist, no SPI module is loaded, and every SPI program fails to open the device:

Raspberry Pi SPI disabled: get_spi returns 1, no /dev/spidev0.0, Python spidev FileNotFoundError and C++ open No such file or directory
Raspberry Pi SPI disabled: get_spi returns 1, no /dev/spidev0.0, Python spidev FileNotFoundError and C++ open No such file or directory

There are three ways to enable it. All three set the same line in config.txt. The two raspi-config methods also apply it right away, so SPI works without a reboot on my Pi 5; a manual edit applies at the next boot.

Method 1: Enable SPI With raspi-config

#1

Run sudo raspi-config, select 3 Interface Options, and press Enter.

raspi-config main menu on the Raspberry Pi 5 with 3 Interface Options selected

#2

Select I4 SPI and press Enter.

raspi-config Interface Options menu with I4 SPI selected

#3

Choose <Yes> when asked “Would you like the SPI interface to be enabled?” (the cursor starts on <No>: press the Left arrow).

raspi-config: Would you like the SPI interface to be enabled? with Yes selected

#4

raspi-config confirms “The SPI interface is enabled”. Press Enter, then select <Finish>.

raspi-config confirmation: The SPI interface is enabled

Method 2: Enable SPI From the Command Line (raspi-config nonint)

For scripts and headless setups, raspi-config has a non-interactive mode. do_spi 0 enables SPI, do_spi 1 disables it, and get_spi prints 0 when it’s enabled:

Raspberry Pi enable SPI from the command line: raspi-config nonint do_spi 1 and 0 switch dtparam=spi off and on and /dev/spidev0.0 appears without a reboot
Raspberry Pi enable SPI from the command line: raspi-config nonint do_spi 1 and 0 switch dtparam=spi off and on and /dev/spidev0.0 appears without a reboot

Method 3: Enable SPI in config.txt (dtparam=spi=on)

On a fresh image, config.txt already contains the line, commented out: #dtparam=spi=on. Open the file with sudo nano /boot/firmware/config.txt, remove the #, save, and reboot:

Raspberry Pi config.txt dtparam=spi=on after a reboot: /dev/spidev0.0 and /dev/spidev0.1 exist
Raspberry Pi config.txt dtparam=spi=on after a reboot: /dev/spidev0.0 and /dev/spidev0.1 exist

On current Raspberry Pi OS the file is /boot/firmware/config.txt; /boot/config.txt is the location from older releases. You don’t need to edit /etc/modprobe.d/raspi-blacklist.conf anymore, a step from the Raspbian days: the spidev module loads by itself. And on the Pi 5, lsmod | grep spi shows spi_dw_mmio and spidev, not spi_bcm2835.

Check the SPI Group (No sudo Needed)

/dev/spidev0.0 and /dev/spidev0.1 belong to the spi group, and the user created by Raspberry Pi Imager is already a member, so Python and C++ programs work without sudo:

Raspberry Pi /dev/spidev0.0 belongs to the spi group and the default user is a member: no sudo needed
Raspberry Pi /dev/spidev0.0 belongs to the spi group and the default user is a member: no sudo needed


Raspberry Pi SPI Modes (CPOL and CPHA)

Every SPI device expects the clock in one of four SPI modes, set by two bits. CPOL (clock polarity) is the level SCLK idles at: 0 = LOW, 1 = HIGH. CPHA (clock phase) says which edge samples the data: 0 = the first edge after CS falls, 1 = the second edge. Data goes out MSB first (bit 7 first) unless the device says otherwise. The device’s datasheet tells you which modes it supports; the BMP280 supports modes 0 and 3, per its datasheet.

Raspberry Pi SPI modes 0 to 3 timing diagram: CPOL idle level, CPHA sampling edge, byte 0xD0 sent MSB first

This is the same chip-ID read on my oscilloscope in all four modes. CH1 (yellow) is SCLK on GPIO11, CH2 (magenta) is MOSI on GPIO10, CH3 (cyan) is MISO on GPIO9, and CH4 (green) is CE0 on GPIO8. The bottom bar is the oscilloscope’s SPI decoder.

Raspberry Pi SPI modes 0, 1, 2 and 3 on the oscilloscope: BMP280 chip-ID read, SCLK idle level and sampling edge per mode, 0x58 only in modes 0 and 3
Raspberry Pi SPI modes 0, 1, 2 and 3 on the oscilloscope: BMP280 chip-ID read, SCLK idle level and sampling edge per mode, 0x58 only in modes 0 and 3

In modes 0 and 1, SCLK idles LOW; in modes 2 and 3, it idles HIGH. The Raspberry Pi sends 0xD0 correctly in every mode, but the BMP280 only answers with 0x58 in modes 0 and 3. In modes 1 and 2, it stays silent, and the Pi reads garbage. A wrong mode never produces an error message: it produces wrong data.


Raspberry Pi SPI Wiring (BMP280 and Loopback)

For the examples, I use the same purple 6-pin BMP280 module as in my I2C tutorial. Its two extra pins make it an SPI device: CSB is the chip select, and SDO becomes MISO. The module’s SDA pin is the SPI data input (SDI, from MOSI), and its SCL pin is the SPI clock (SCK). The sensor itself gets its own tutorial; here it’s used as a standard SPI device.

QTY.Component NameAmazon.comAliExpress
1Raspberry Pi 5 (4GB or 8GB)AmazonAliExpress
1Raspberry Pi 27W USB-C Power SupplyAmazonAliExpress
1BMP280 6-Pin SPI/I2C Module (3.3v)AmazonAliExpress
1BreadboardAmazonAliExpress
1Jumper Wires (Female-Male + Male-Male)AmazonAliExpress

BMP280 in SPI Mode

Raspberry Pi SPI wiring diagram: BMP280 module to Raspberry Pi 5 SPI0, SDA to GPIO10 MOSI pin 19, SDO to GPIO9 MISO pin 21, SCL to GPIO11 SCLK pin 23, CSB to GPIO8 CE0 pin 24

BMP280 Module Raspberry Pi 5 VCC (via + rail) 3.3v (pin 1) GND GND (pin 9) SDA (SDI) GPIO10 MOSI (pin 19) SDO GPIO9 MISO (pin 21) SCL (SCK) GPIO11 SCLK (pin 23) CSB GPIO8 CE0 (pin 24)

Six wires: power, ground, and the four SPI lines. The BMP280 picks its interface from CSB: the first time CSB goes LOW, the chip switches to SPI and stays in SPI mode until its power is removed, per the BMP280 datasheet. So once you’ve used it over SPI, power-cycle it before you use it over I2C again.

The BMP280’s data input goes to GPIO10 (MOSI), its SDO output to GPIO9 (MISO), its clock input to GPIO11 (SCLK), and CSB to GPIO8 (CE0). Power comes from 3.3v and GND.

SPI Loopback Wiring (MOSI to MISO)

A loopback test checks the SPI controller, the pins, and your code without any device: a jumper connects MOSI to MISO, so every byte the Pi sends comes straight back. I put the jumper between the BMP280’s SDO and SDA columns on the breadboard and ran the loopback on CE1 ( /dev/spidev0.1), so the sensor on CE0 stays deselected and doesn’t drive MISO. Take the jumper out before you talk to the sensor: it would short the sensor’s SDO output to the Pi’s MOSI.

Raspberry Pi SPI loopback wiring: jumper from MOSI (GPIO10) to MISO (GPIO9) through the breadboard, test on CE1 with the BMP280 deselected

Breadboard Raspberry Pi 5 SDA (SDI) column GPIO10 MOSI (pin 19) SDO column GPIO9 MISO (pin 21) Jumper SDO ↔ SDA MOSI ↔ MISO

The Jumper connects the column of GPIO10 (MOSI) to the column of GPIO9 (MISO). Without a breadboard, one female-female jumper from pin 19 to pin 21 does the same.


Raspberry Pi SPI Python (spidev)

spidev (py-spidev) is the Python module for Linux SPI, and Raspberry Pi OS ships it as python3-spidev (version 3.6 on Trixie). If it’s missing on another image, install it with sudo apt install python3-spidev. Don’t run pip install spidev into the system Python: current Raspberry Pi OS blocks it (PEP 668):

Raspberry Pi spidev 3.6 is pre-installed (python3-spidev); pip install spidev fails with error: externally-managed-environment
Raspberry Pi spidev 3.6 is pre-installed (python3-spidev); pip install spidev fails with error: externally-managed-environment

If you need a newer release from PyPI (3.8 at the time of writing, per PyPI), use a virtual environment: python3 -m venv --system-site-packages ~/spi-venv, then ~/spi-venv/bin/pip install spidev. The examples here use the packaged 3.6.

Raspberry Pi SPI Python Settings

SettingWhat It DoesOn the Raspberry Pi 5
spi.open(0, 0)Opens /dev/spidev.bus 0, CE0 or CE1; bus 1 with the spi1 overlay
spi.max_speed_hzSCLK frequency in Hz200MHz / even divider (see the speed section)
spi.modeSPI mode 0 to 3all four work
spi.bits_per_wordWord size8, 9, 16, and 32 accepted
spi.lsbfirstLSB firstnot supported: OSError [Errno 22]
spi.cshighActive-HIGH chip selectnot supported: “Attempted to set mode 0x4 but mode 0x0 returned”
spi.no_csDon’t drive any CSnot supported: OSError [Errno 22]
spi.threewireShared MOSI/MISO linenot supported: OSError [Errno 22]

I tested every attribute on my Raspberry Pi 5. The RP1 SPI driver rejects LSB-first, active-HIGH chip selects, no-CS, and 3-wire mode; for an LSB-first device, reverse the bits in your code, and for an active-HIGH or extra chip select, use an overlay parameter ( cs0_pin) or the spi0-1cs-inverted overlay from the overlay README.

xfer2 vs xfer vs writebytes

FunctionWhat It Does
xfer2(list)One transfer: CS stays LOW for the whole list. Returns the received bytes. Use this for register reads and writes
xfer(list)Releases and re-asserts CS between blocks (per the py-spidev README)
xfer3(list)Like xfer2, for lists longer than bufsiz: splits them into bufsiz chunks. Returns a tuple
writebytes(list) / writebytes2(buf)Write only, received bytes discarded; writebytes2 takes bytes and any length
readbytes(n)Clocks out n zero bytes and returns what came back

Note: xfer() and xfer2() overwrite the list you pass them with the received bytes (py-spidev 3.6 on my Raspberry Pi 5; xfer3() doesn’t). If you keep your transmit list to compare or re-send it later, pass a copy: rx = spi.xfer2(list(tx)). My first loopback script compared the data with itself because of this and reported zero errors even without the jumper.

Raspberry Pi SPI Python Loopback Test

Wire the loopback jumper, then send a random buffer and compare every byte that comes back:

Python Code example (Raspberry Pi SPI loopback test with spidev)

Raspberry Pi SPI loopback test output: Python spidev and C++ send 4096 random bytes on /dev/spidev0.1 at 1MHz, 10MHz and 50MHz with 0 errors
Raspberry Pi SPI loopback test output: Python spidev and C++ send 4096 random bytes on /dev/spidev0.1 at 1MHz, 10MHz and 50MHz with 0 errors

Raspberry Pi SPI Python: Read and Write BMP280 Registers

With the jumper removed, this example reads the BMP280’s chip ID, writes one control register (ctrl_meas, 0xF4), and reads it back. The BMP280 uses bit 7 of the first byte as the read/write bit: 1 = read, 0 = write. So a read sends reg | 0x80 and a write sends reg & 0x7F, per the datasheet (section 5.3). Other chips use other conventions, so check yours.

Python Code example (Raspberry Pi SPI register read and write with spidev)

Raspberry Pi SPI Python spidev output: BMP280 chip ID 0x58, raw xfer2 reply 0x00 0x58, ctrl_meas written 0x24 and read back 0x24
Raspberry Pi SPI Python spidev output: BMP280 chip ID 0x58, raw xfer2 reply 0x00 0x58, ctrl_meas written 0x24 and read back 0x24

The raw reply shows the junk byte: ['0x00', '0x58']. The first byte arrived while the Pi was still sending the register address, before the sensor knew what to answer, so the code keeps only rx[1:].


Raspberry Pi SPI C++ (Linux spidev ioctl)

There’s no separate C++ SPI library to install: the standard way is the Linux spidev interface itself, a character device that you open and configure with ioctl() calls, documented in the kernel’s SPI userspace API. The headers ( linux/spi/spidev.h) come with the compiler packages on Raspberry Pi OS. These are the versions on my Raspberry Pi 5:

Raspberry Pi OS Trixie versions: python3-spidev 3.6, g++ 14.2, kernel 6.18.60, linux/spi/spidev.h
Raspberry Pi OS Trixie versions: python3-spidev 3.6, g++ 14.2, kernel 6.18.60, linux/spi/spidev.h

ioctlWhat It Does
SPI_IOC_WR_MODE / SPI_IOC_RD_MODESet / read the SPI mode (SPI_MODE_0 to SPI_MODE_3)
SPI_IOC_WR_MAX_SPEED_HZSet the default SCLK frequency
SPI_IOC_WR_BITS_PER_WORDSet the word size (8 by default)
SPI_IOC_MESSAGE(n)Run n spi_ioc_transfer segments as one full-duplex transfer (CS stays LOW unless cs_change is set)

A Small C++ SPI Class

This header wraps the open call, the three settings, and one full-duplex transfer in a class. The examples below use it:

C++ Code example (spi_device.hpp, a C++ wrapper for Linux spidev)

Raspberry Pi SPI C++ Loopback Test

C++ Code example (Raspberry Pi SPI loopback test in C++)

The output is in the loopback screenshot above. For a reference test, the kernel’s own spidev_test (tools/spi/spidev_test.c) builds on the Pi in seconds with gcc -O2 spidev_test.c -o spidev_test; with the jumper in place, every byte it sends comes back:

Raspberry Pi spidev_test loopback on /dev/spidev0.1 at 1MHz: TX and RX bytes match
Raspberry Pi spidev_test loopback on /dev/spidev0.1 at 1MHz: TX and RX bytes match

Raspberry Pi SPI C++: Read and Write BMP280 Registers

C++ Code example (Raspberry Pi SPI register read and write in C++)

Build it with g++, and run it without sudo:

Raspberry Pi SPI C++ build and run: g++ bmp280_spi.cpp, chip ID 0x58, raw reply 0x00 0x58, ctrl_meas 0x24 read back
Raspberry Pi SPI C++ build and run: g++ bmp280_spi.cpp, chip ID 0x58, raw reply 0x00 0x58, ctrl_meas 0x24 read back

Here is that chip-ID read on my oscilloscope, zoomed in on the two bytes. The decoder shows 0xD0 0x00 on MOSI and 0x00 0x58 on MISO:

Raspberry Pi SPI BMP280 chip-ID read on the oscilloscope with SPI decode: MOSI 0xD0 0x00, MISO 0x00 0x58, mode 0, 1MHz
Raspberry Pi SPI BMP280 chip-ID read on the oscilloscope with SPI decode: MOSI 0xD0 0x00, MISO 0x00 0x58, mode 0, 1MHz

During the first byte, MISO isn’t driven at all (the sensor is still receiving the address), which is where the junk 0x00 comes from. During the second byte, the sensor drives MISO with 0x58 = 0101 1000, MSB first, while the Pi sends a dummy 0x00.


Raspberry Pi SPI Speed: max_speed_hz vs the Real Clock

On the Raspberry Pi 5, max_speed_hz is an upper limit, not the clock you get. RP1 clocks its SPI controllers from a 200MHz clock ( clk_sys on my board) and divides it by an even number, rounding so that SCLK never goes above what you asked for. The DesignWare driver computes it like this (spi-dw-core.c, rpi-6.18.y):

I measured SCLK on my oscilloscope for a range of max_speed_hz values (CH1 on GPIO11; 1X probe up to 12.5MHz, 10X above), with the loopback running on CE1:

max_speed_hzDividerExpected SCLKMeasured SCLK
1000002000100kHz100.0kHz
500000400500kHz500.0kHz
10000002001MHz1.000MHz
20000001002MHz2.000MHz
4000000504MHz4.000MHz
8000000267.69MHz7.69MHz
125000001612.5MHz12.54MHz
160000001414.29MHz14.29MHz
200000001020MHz20.00MHz
25000000825MHz24.98MHz
32000000825MHz25.00MHz
40000000633.33MHz33.33MHz
50000000450MHz50.00MHz
66666666450MHz50.00MHz

Every measurement matches the rule. The bold rows are the surprises: asking for 32MHz gives 25MHz, and asking for 40MHz gives 33.33MHz. If a device’s maximum is, say, 10MHz, ask for exactly 10MHz (divider 20); asking for 9MHz gives 8.33MHz (divider 24). The slowest possible clock is 200MHz / 65534 ≈ 3.05kHz.

On the Raspberry Pi 4 and older, the SPI clock is the core clock divided by an even divider (CDIV), per the Raspberry Pi documentation, so speed tables made on those boards don’t apply to the Pi 5.

Maximum SPI Speed With Zero Errors

To find the fastest usable clock, I sent 1MB of random data through the loopback jumper at each speed, five times, in 64KB transfers, and counted every bit that came back wrong ( spi_bench.cpp in the download):

max_speed_hzReal SCLKBytes CheckedBit ErrorsC++ Throughput
10000001MHz1.3MB0125.0kB/s
40000004MHz5.2MB0499.7kB/s
1000000010MHz5.2MB01,248kB/s
2000000020MHz5.2MB02,493kB/s
2500000025MHz5.2MB03,115kB/s
4000000033.33MHz21MB4 (in the first run only)4,148kB/s
5000000050MHz21MB06,209kB/s
100000000100MHz5.2MB20,971,657 (unusable)–

With my short breadboard wiring, SPI on the Raspberry Pi 5 runs error-free up to 50MHz. The one run with 4 bit errors at 33.33MHz didn’t repeat in three more runs (15MB, zero errors), so treat speeds above about 20MHz as wiring-dependent and test your own setup. At 100MHz (divider 2) almost every byte is wrong. Real devices are usually the limit long before the Pi: the BMP280’s maximum is 10MHz, per its datasheet.

Raspberry Pi SPI Throughput: Python vs C++

For large transfers, the clock runs without gaps: at 50MHz, C++ moves 6,209kB/s, 99.3% of the 6,250kB/s the wire can carry. Python gets close for large blocks and falls far behind for small ones (median of five runs, 1MB of data):

Method (Python spidev)10MHz50MHz
xfer2(), 4096-byte chunks1,195kB/s5,080kB/s
xfer3(), one 1MB call1,213kB/s3,456kB/s
writebytes2(), one 1MB call (write only)1,249kB/s3,837kB/s
xfer2() of 1 byte, time per call26.9µs22.8µs
C++ SPI_IOC_MESSAGE, 64KB transfers1,248kB/s6,209kB/s

A one-byte xfer2() call takes about 23-27µs whatever the clock, so code that sends one byte per call is limited to about 40,000 bytes per second, even at 50MHz. Collect your bytes into one list and send them in one call. This capture shows the clock running without a gap between bytes in the middle of a 64-byte xfer2() at 10MHz:

Raspberry Pi SPI 10MHz burst on the oscilloscope: SCLK runs continuously with no gap between bytes during a 64-byte xfer2
Raspberry Pi SPI 10MHz burst on the oscilloscope: SCLK runs continuously with no gap between bytes during a 64-byte xfer2

Chip Select Timing on the Raspberry Pi 5

Because CE0 and CE1 are GPIO-driven, each transfer has a fixed overhead around the clock pulses. This capture is the 2-byte chip-ID read at 1MHz from Python:

Raspberry Pi 5 SPI chip select timing on the oscilloscope: 16.5µs from CS low to the first clock and 13.3µs from the last clock to CS high for a 2-byte read
Raspberry Pi 5 SPI chip select timing on the oscilloscope: 16.5µs from CS low to the first clock and 13.3µs from the last clock to CS high for a 2-byte read

Over seven single shots each, the time from CS falling to the first clock was 16.8µs median in C++ (15.8–18.8µs) and 20.0µs in Python (16.3–24.5µs), and from the last clock to CS rising 14.6µs (C++) and 12.9µs (Python). So a 2-byte read holds CS LOW for about 46µs, of which only 16µs is clocking. For devices this is harmless (they just wait), but it means many small transfers are slow: group them.


Raspberry Pi SPI Transfer Size: The 4096-Byte bufsiz Limit

The spidev driver copies every transfer through a buffer of 4096 bytes by default (the bufsiz module parameter, “one page” in the kernel documentation). A longer transfer fails. In Python, xfer2() refuses anything over 4096 bytes before it even reaches the kernel, and in C++ the ioctl fails with EMSGSIZE:

Raspberry Pi spidev bufsiz 4096: Python xfer2 OverflowError Argument list size exceeds 4096 bytes and C++ SPI_IOC_MESSAGE Message too long
Raspberry Pi spidev bufsiz 4096: Python xfer2 OverflowError Argument list size exceeds 4096 bytes and C++ SPI_IOC_MESSAGE Message too long

You can raise the limit without a reboot by reloading the module with a new value (SPI must not be in use at that moment):

Raspberry Pi raise spidev bufsiz without a reboot: modprobe spidev bufsiz=65536, a 65536-byte C++ transfer works and 65537 bytes give Message too long
Raspberry Pi raise spidev bufsiz without a reboot: modprobe spidev bufsiz=65536, a 65536-byte C++ transfer works and 65537 bytes give Message too long

To make it permanent, add spidev.bufsiz=65536 to the single line in /boot/firmware/cmdline.txt and reboot. I tested it on my Raspberry Pi 5: after the reboot, /sys/module/spidev/parameters/bufsiz reads 65536. Two things surprised me there:

Raspberry Pi spidev.bufsiz=65536 on the kernel command line: Python xfer2 still limited to 4096 bytes and 65536 bytes gives TypeError Empty argument list, xfer3 works
Raspberry Pi spidev.bufsiz=65536 on the kernel command line: Python xfer2 still limited to 4096 bytes and 65536 bytes gives TypeError Empty argument list, xfer3 works

  • Python’s xfer() and xfer2() stay limited to 4096 bytes whatever bufsiz is, and a list of exactly 65536 bytes fails with a misleading TypeError: Empty argument list. (py-spidev 3.6). For big Python transfers, use xfer3() or writebytes2(), which split the data into bufsiz-sized chunks for you (CS is released between chunks).
  • Once spidev.bufsiz is on the kernel command line, reloading the module without a value still gives 65536: the kernel keeps applying its command-line value until the next boot.

In C++, keep each spi_ioc_transfer at or under bufsiz, or split a long transfer into several segments of one SPI_IOC_MESSAGE.


Raspberry Pi SPI vs Arduino SPI

If you’re coming from microcontrollers, here is how the Arduino SPI calls map to the Raspberry Pi:

Arduino (SPI library)Python (spidev)C++ (Linux spidev)
SPI.begin()spi.open(0, 0)fd = open("/dev/spidev0.0", O_RDWR)
SPISettings(1000000, MSBFIRST, SPI_MODE0)spi.max_speed_hz = 1000000; spi.mode = 0ioctl(fd, SPI_IOC_WR_MODE / WR_MAX_SPEED_HZ, ...)
digitalWrite(CS, LOW) + beginTransaction()done by xfer2()done by SPI_IOC_MESSAGE
SPI.transfer(b)spi.xfer2([b])spi_ioc_transfer with len = 1
SPI.transfer(buf, n)spi.xfer2(list(buf))spi_ioc_transfer with len = n

The big difference: on Linux, the kernel drives the chip select for you, a transfer is one system call, and each call costs about 20µs, so you send whole buffers instead of one byte at a time. For the microcontroller side, see my STM32 SPI tutorial, and for the SPI protocol in more depth, my SPI tutorial.


Raspberry Pi SPI Troubleshooting

These are the errors and wrong readings I hit on the Raspberry Pi 5, with their causes and fixes.

No /dev/spidev0.0 (FileNotFoundError, No such file or directory)

SPI is disabled. Enable it with any of the three methods above; the error output is in the enable section. If /dev/spidev0.0 exists but /dev/spidev0.1 doesn’t, an overlay such as spi0-1cs is in config.txt.

Readings That Make No Sense (Wrong SPI Mode)

A wrong SPI mode gives no error, just wrong data. My BMP280 answers 0x58 in modes 0 and 3, and garbage that even changes between runs (0x00 or 0x72) in modes 1 and 2:

Raspberry Pi SPI wrong mode: BMP280 chip ID read returns 0x58 in modes 0 and 3 and 0x72 in modes 1 and 2
Raspberry Pi SPI wrong mode: BMP280 chip ID read returns 0x58 in modes 0 and 3 and 0x72 in modes 1 and 2

Check the device datasheet for its mode and its bit order. The RP1 driver doesn’t support LSB-first, so an LSB-first device needs its bits reversed in code.

All 0x00 or All 0xFF (Loose or Missing MISO)

If every byte reads 0x00 or 0xFF, nothing is driving MISO: the wire is loose, on the wrong pin, or the device isn’t selected or powered. I unplugged the MISO wire to show it. A floating MISO reads 0x00 on my Pi 5; with the pin’s pull-up turned on, the same fault reads 0xFF:

Raspberry Pi SPI loose MISO wire: BMP280 chip ID reads 0x00 with MISO floating and 0xFF with the GPIO9 pull-up enabled
Raspberry Pi SPI loose MISO wire: BMP280 chip ID reads 0x00 with MISO floating and 0xFF with the GPIO9 pull-up enabled

A loopback test (MOSI to MISO) tells you whether the Pi side works; if it passes, the problem is on the device side.

PermissionError: [Errno 13] Permission denied

Raspberry Pi spidev PermissionError Errno 13 Permission denied for a user that isn't in the spi group
Raspberry Pi spidev PermissionError Errno 13 Permission denied for a user that isn’t in the spi group

The user isn’t in the spi group. Add it with sudo usermod -aG spi $USER and log in again. Don’t work around it with sudo in every command.

GPIO8 or GPIO7 Busy (Device or Resource Busy)

While SPI is on, the SPI driver owns CE0 and CE1. gpioinfo shows them as consumer="spi0 CS0" and "spi0 CS1", and any GPIO library that requests them fails (gpiozero reports lgpio.error: 'GPIO busy'):

Raspberry Pi SPI chip select busy: gpioinfo shows GPIO8 consumer spi0 CS0 and gpioset fails with Device or resource busy
Raspberry Pi SPI chip select busy: gpioinfo shows GPIO8 consumer spi0 CS0 and gpioset fails with Device or resource busy

Use other pins for GPIO, move the chip selects with spi0-2cs, or free GPIO7 with spi0-1cs. The opposite case is worse: an overlay that wants a pin SPI0 already uses ( spi3-1cs-pi5 and GPIO7) takes it without any error, as shown in the pins section.

Argument list size exceeds 4096 bytes / Message too long

The transfer is bigger than spidev’s buffer. Use xfer3() in Python, split the transfer, or raise bufsiz as shown in the bufsiz section.

A Device Misbehaves After You Change SPI Modes

When two devices on the same bus use different modes, look at the clock when the mode changes. On my Raspberry Pi 5, SCLK switches to the new idle level only after CS has already gone LOW: going from mode 3 to mode 0, SCLK falls 0.6µs after CS falls, so the selected device sees one extra clock edge:

Raspberry Pi 5 SPI mode change on the oscilloscope: SCLK drops from the mode 3 idle level 0.6µs after CS falls, an extra edge inside the transfer
Raspberry Pi 5 SPI mode change on the oscilloscope: SCLK drops from the mode 3 idle level 0.6µs after CS falls, an extra edge inside the transfer

My BMP280 ignored it, but a device that counts every edge can shift its data by one bit. If you mix modes on one bus, send a dummy transfer to a free chip select (CE1) after each mode change, or give the devices with different modes their own bus (SPI1).


Raspberry Pi SPI FAQ

Does the Raspberry Pi have SPI?

Yes. Every Raspberry Pi with a 40-pin header has SPI0 on GPIO7 to GPIO11. The Raspberry Pi 5 can route five SPI controllers to the header (SPI0, SPI1, SPI2, SPI3, and SPI5) with overlays.

How many SPI buses does the Raspberry Pi 5 have?

SPI0 is enabled with dtparam=spi=on. SPI1, SPI2, SPI3, and SPI5 can be added with the overlays in the pins section; SPI2, SPI3, and SPI5 share pins with I2C1, SPI0’s CE1, or the UART.

What is the maximum SPI speed on the Raspberry Pi 5?

The controller can clock at 100MHz (200MHz / 2), but my loopback test failed there. It ran error-free at 50MHz, the next step down. Most devices top out at 10MHz to 20MHz anyway.

Do I need sudo for SPI on the Raspberry Pi?

No. On current Raspberry Pi OS, your user is in the spi group, which owns /dev/spidev*.

Can I use any GPIO as a chip select?

Almost: the chip selects are GPIOs on the Raspberry Pi 5, so the cs0_pin / cs1_pin overlay parameters accept any free pin. The pin must not be in use by anything else.

Is SPI better than I2C?

Neither is better; they suit different jobs. SPI is faster and simpler but needs more pins; I2C needs only two wires for many devices. See the comparison box at the top of this tutorial.


Download Raspberry Pi SPI Examples

The download contains every example from this tutorial in Python and C++: the quick examples, the loopback tests, the BMP280 register examples, and the spidev C++ class, plus the benchmark programs behind the measurements, with a README that lists each command.

Download Raspberry Pi SPI Examples (Python, C++)

Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.


Wrap Up

To conclude this tutorial, we’ve enabled Raspberry Pi SPI on the Raspberry Pi 5 three ways, wired a loopback and a BMP280, and read and written its registers with spidev in Python and C++. The measurements show what to expect from the bus: max_speed_hz lands on 200MHz divided by an even number, the bus runs error-free up to 50MHz on short wires, and large transfers in one call reach the full wire speed, while one-byte calls cost about 20µs each.

For the GPIO basics, see my Raspberry Pi GPIO tutorial, and for the two-wire bus, the Raspberry Pi I2C tutorial. The next tutorials in this Raspberry Pi series cover UART, and full projects with SPI displays, ADCs, and radio modules. For an SPI display you can build today, see my Raspberry Pi e-ink display tutorial (Python and C++). For a small display on the I2C bus instead, see the Raspberry Pi OLED display tutorial.

Share This Page With Your Network!
Join Our +25,000 Newsletter Subscribers!

Stay Updated With All New Content Releases. You Also Get Occasional FREE Coupon Codes For Courses & Other Stuff!

Photo of author
Author
Embedded systems engineer with several years of experience in embedded software and hardware design. I work as an embedded SW engineer in the Automotive & e-Mobility industry. However, I still do Hardware design and SW development for DSP, Control Systems, Robotics, AI/ML, and other fields I'm passionate about.
I love reading, writing, creating projects, and teaching. A reader by day and a writer by night, it's my lifestyle. I believe that the combination of brilliant minds, bold ideas, and a complete disregard for what is possible, can and will change the world! I will be there when it happens, will you?

Leave a Comment