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)
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#!/usr/bin/env python3 # Raspberry Pi SPI quick test: read the BMP280 chip ID over SPI0 (CE0) import spidev spi = spidev.SpiDev() spi.open(0, 0) # /dev/spidev0.0 = SPI0, chip select CE0 (GPIO8) spi.max_speed_hz = 1000000 # 1MHz SCLK spi.mode = 0 # CPOL=0, CPHA=0 rx = spi.xfer2([0xD0 | 0x80, 0x00]) # bit 7 = 1 -> read register 0xD0 (chip ID) print(f"Chip ID: 0x{rx[1]:02X}") # rx[0] is clocked in while the address goes out spi.close() |
C++ Code example (Raspberry Pi SPI read with the Linux spidev ioctl)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Raspberry Pi SPI quick test: read the BMP280 chip ID over SPI0 (CE0) with the Linux spidev ioctl #include <cstdio> #include <fcntl.h> #include <linux/spi/spidev.h> #include <sys/ioctl.h> #include <unistd.h> int main() { int fd = open("/dev/spidev0.0", O_RDWR); // SPI0, chip select CE0 (GPIO8) if (fd < 0) { perror("open /dev/spidev0.0"); return 1; } unsigned char tx[2] = {0xD0 | 0x80, 0x00}, rx[2] = {}; // bit 7 = 1 -> read register 0xD0 spi_ioc_transfer t{}; t.tx_buf = (unsigned long)tx; t.rx_buf = (unsigned long)rx; t.len = 2; t.speed_hz = 1000000; t.bits_per_word = 8; // 1MHz, mode 0 is the default if (ioctl(fd, SPI_IOC_MESSAGE(1), &t) < 0) { perror("SPI_IOC_MESSAGE"); return 1; } printf("Chip ID: 0x%02X\n", rx[1]); // rx[0] is clocked in while the address goes out close(fd); } |
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 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.

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 Pin | GPIO | SPI0 Function | Linux Device |
|---|---|---|---|
| Pin 19 | GPIO10 | MOSI | – |
| Pin 21 | GPIO9 | MISO | – |
| Pin 23 | GPIO11 | SCLK | – |
| Pin 24 | GPIO8 | CE0 (chip select 0) | /dev/spidev0.0 |
| Pin 26 | GPIO7 | CE1 (chip select 1) | /dev/spidev0.1 |
| Pin 1 / 17 | – | 3.3v | Power for 3.3v SPI modules |
| Pin 6, 9, 20, 25, … | – | GND | Common 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:
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) | SCLK | MOSI | MISO | Chip Selects | Conflicts |
|---|---|---|---|---|---|
dtparam=spi=on | GPIO11 | GPIO10 | GPIO9 | GPIO8, GPIO7 | – |
spi1-1cs / -2cs / -3cs | GPIO21 | GPIO20 | GPIO19 | GPIO18, GPIO17, GPIO16 | I2S / PCM pins |
spi2-1cs-pi5 / -2cs-pi5 | GPIO3 | GPIO2 | GPIO1 | GPIO0, GPIO24 | I2C1 and the HAT EEPROM pins |
spi3-1cs-pi5 / -2cs-pi5 | GPIO7 | GPIO6 | GPIO5 | GPIO4, GPIO25 | SCLK is SPI0’s CE1 |
spi5-1cs / -2cs | GPIO15 | GPIO14 | GPIO13 | GPIO12, GPIO26 | UART0 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:
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:
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:
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.

#2
Select I4 SPI and press Enter.

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

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

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:
|
1 |
sudo raspi-config nonint do_spi 0 |
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:
|
1 |
dtparam=spi=on |
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 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.

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.
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 Name | Amazon.com | AliExpress |
|---|---|---|---|
| 1 | Raspberry Pi 5 (4GB or 8GB) | Amazon | AliExpress |
| 1 | Raspberry Pi 27W USB-C Power Supply | Amazon | AliExpress |
| 1 | BMP280 6-Pin SPI/I2C Module (3.3v) | Amazon | AliExpress |
| 1 | Breadboard | Amazon | AliExpress |
| 1 | Jumper Wires (Female-Male + Male-Male) | Amazon | AliExpress |
BMP280 in SPI Mode

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.

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):
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
| Setting | What It Does | On 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_hz | SCLK frequency in Hz | 200MHz / even divider (see the speed section) |
spi.mode | SPI mode 0 to 3 | all four work |
spi.bits_per_word | Word size | 8, 9, 16, and 32 accepted |
spi.lsbfirst | LSB first | not supported: OSError [Errno 22] |
spi.cshigh | Active-HIGH chip select | not supported: “Attempted to set mode 0x4 but mode 0x0 returned” |
spi.no_cs | Don’t drive any CS | not supported: OSError [Errno 22] |
spi.threewire | Shared MOSI/MISO line | not 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
| Function | What 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)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#!/usr/bin/env python3 # Raspberry Pi SPI loopback test with spidev (jumper MOSI GPIO10 -> MISO GPIO9) # Sends a random buffer and checks that every byte comes back unchanged. # python3 spi_loopback.py [speed_hz] [mode] [length] import os, sys, spidev SPEED = int(sys.argv[1]) if len(sys.argv) > 1 else 1000000 MODE = int(sys.argv[2]) if len(sys.argv) > 2 else 0 LENGTH = int(sys.argv[3]) if len(sys.argv) > 3 else 4096 spi = spidev.SpiDev() spi.open(0, 1) # /dev/spidev0.1 = CE1 (GPIO7), so the BMP280 on CE0 stays deselected spi.max_speed_hz = SPEED spi.mode = MODE spi.bits_per_word = 8 tx = list(os.urandom(LENGTH)) rx = spi.xfer2(list(tx)) # full duplex, CS held low for the whole buffer. Pass a copy: xfer2() overwrites # the list you give it with the received bytes errors = sum(a != b for a, b in zip(tx, rx)) print(f"mode {MODE}, {SPEED} Hz, {LENGTH} bytes: sent {bytes(tx[:4]).hex(' ')} ..., " f"got {bytes(rx[:4]).hex(' ')} ..., errors: {errors}") spi.close() sys.exit(1 if errors else 0) |
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)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#!/usr/bin/env python3 # Raspberry Pi SPI register read/write with spidev (BMP280 as the example device) # Reads the chip ID, writes one control register and reads it back. import spidev REG_CHIP_ID = 0xD0 # reads 0x58 on a BMP280 (0x60 on a BME280) REG_CTRL_MEAS = 0xF4 # osrs_t[7:5] osrs_p[4:2] mode[1:0] spi = spidev.SpiDev() spi.open(0, 0) # SPI0, CE0 -> BMP280 CSB spi.max_speed_hz = 1000000 # the BMP280 takes up to 10MHz spi.mode = 0 # the BMP280 accepts mode 0 and mode 3 def read_reg(reg, n=1): # Read: register address with bit 7 = 1, then n dummy bytes to clock the data out rx = spi.xfer2([reg | 0x80] + [0x00] * n) return rx[1:] # rx[0] arrived while the address byte was going out: ignore it def write_reg(reg, value): # Write: register address with bit 7 = 0, then the value spi.xfer2([reg & 0x7F, value]) print(f"Chip ID: 0x{read_reg(REG_CHIP_ID)[0]:02X}") print("Raw xfer2 reply for the chip ID read:", [f"0x{b:02X}" for b in spi.xfer2([REG_CHIP_ID | 0x80, 0x00])]) before = read_reg(REG_CTRL_MEAS)[0] write_reg(REG_CTRL_MEAS, 0x24) # osrs_t x1, osrs_p x1, sleep mode after = read_reg(REG_CTRL_MEAS)[0] print(f"ctrl_meas: 0x{before:02X} -> wrote 0x24 -> read back 0x{after:02X}") write_reg(REG_CTRL_MEAS, before) # restore the old value spi.close() |
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:
| ioctl | What It Does |
|---|---|
SPI_IOC_WR_MODE / SPI_IOC_RD_MODE | Set / read the SPI mode (SPI_MODE_0 to SPI_MODE_3) |
SPI_IOC_WR_MAX_SPEED_HZ | Set the default SCLK frequency |
SPI_IOC_WR_BITS_PER_WORD | Set 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)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// spi_device.hpp - a small C++ wrapper around the Linux spidev interface (/dev/spidevB.C) #pragma once #include <cerrno> #include <cstdint> #include <cstring> #include <fcntl.h> #include <linux/spi/spidev.h> #include <stdexcept> #include <string> #include <sys/ioctl.h> #include <unistd.h> #include <vector> class SpiDevice { public: SpiDevice(const std::string& path, uint32_t speed_hz, uint8_t mode = SPI_MODE_0, uint8_t bits = 8) : speed_(speed_hz), bits_(bits) { fd_ = ::open(path.c_str(), O_RDWR); if (fd_ < 0) throw std::runtime_error("open " + path + ": " + std::strerror(errno)); if (ioctl(fd_, SPI_IOC_WR_MODE, &mode) < 0) fail("SPI_IOC_WR_MODE"); if (ioctl(fd_, SPI_IOC_WR_BITS_PER_WORD, &bits_) < 0) fail("SPI_IOC_WR_BITS_PER_WORD"); if (ioctl(fd_, SPI_IOC_WR_MAX_SPEED_HZ, &speed_) < 0) fail("SPI_IOC_WR_MAX_SPEED_HZ"); } ~SpiDevice() { if (fd_ >= 0) ::close(fd_); } SpiDevice(const SpiDevice&) = delete; SpiDevice& operator=(const SpiDevice&) = delete; // Full duplex: clocks tx out on MOSI and returns the same number of bytes read on MISO. // CS stays low for the whole buffer. std::vector<uint8_t> transfer(const std::vector<uint8_t>& tx) { std::vector<uint8_t> rx(tx.size()); spi_ioc_transfer t{}; t.tx_buf = reinterpret_cast<uintptr_t>(tx.data()); t.rx_buf = reinterpret_cast<uintptr_t>(rx.data()); t.len = static_cast<uint32_t>(tx.size()); t.speed_hz = speed_; t.bits_per_word = bits_; if (ioctl(fd_, SPI_IOC_MESSAGE(1), &t) < 0) fail("SPI_IOC_MESSAGE"); return rx; } private: [[noreturn]] void fail(const char* what) { throw std::runtime_error(std::string(what) + ": " + std::strerror(errno)); } int fd_ = -1; uint32_t speed_; uint8_t bits_; }; |
Raspberry Pi SPI C++ Loopback Test
C++ Code example (Raspberry Pi SPI loopback test in C++)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Raspberry Pi SPI loopback test with spidev in C++ (jumper MOSI GPIO10 -> MISO GPIO9) // ./spi_loopback [speed_hz] [mode] [length] #include "spi_device.hpp" #include <cstdio> #include <cstdlib> #include <random> int main(int argc, char** argv) { uint32_t speed = argc > 1 ? std::strtoul(argv[1], nullptr, 0) : 1000000; uint8_t mode = argc > 2 ? std::atoi(argv[2]) : 0; size_t length = argc > 3 ? std::strtoul(argv[3], nullptr, 0) : 4096; try { SpiDevice spi("/dev/spidev0.1", speed, mode); // CE1: the BMP280 on CE0 stays deselected std::vector<uint8_t> tx(length); std::mt19937 rng(std::random_device{}()); for (auto& b : tx) b = rng() & 0xFF; auto rx = spi.transfer(tx); size_t errors = 0; for (size_t i = 0; i < length; i++) errors += (tx[i] != rx[i]); printf("mode %u, %u Hz, %zu bytes: sent %02x %02x %02x %02x ..., got %02x %02x %02x %02x ..., errors: %zu\n", mode, speed, length, tx[0], tx[1], tx[2], tx[3], rx[0], rx[1], rx[2], rx[3], errors); return errors ? 1 : 0; } catch (const std::exception& e) { fprintf(stderr, "%s\n", e.what()); return 2; } } |
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 SPI C++: Read and Write BMP280 Registers
C++ Code example (Raspberry Pi SPI register read and write in C++)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// Raspberry Pi SPI register read/write in C++ (Linux spidev, BMP280 as the example device) #include "spi_device.hpp" #include <cstdio> constexpr uint8_t REG_CHIP_ID = 0xD0; // reads 0x58 on a BMP280 (0x60 on a BME280) constexpr uint8_t REG_CTRL_MEAS = 0xF4; // osrs_t[7:5] osrs_p[4:2] mode[1:0] int main() { try { SpiDevice spi("/dev/spidev0.0", 1000000, SPI_MODE_0); // SPI0 CE0, 1MHz, mode 0 // Read: address with bit 7 = 1, one dummy byte; rx[0] arrives while the address goes out auto read_reg = [&](uint8_t reg) { return spi.transfer({uint8_t(reg | 0x80), 0x00})[1]; }; // Write: address with bit 7 = 0, then the value auto write_reg = [&](uint8_t reg, uint8_t v) { spi.transfer({uint8_t(reg & 0x7F), v}); }; printf("Chip ID: 0x%02X\n", read_reg(REG_CHIP_ID)); auto raw = spi.transfer({REG_CHIP_ID | 0x80, 0x00}); printf("Raw transfer reply for the chip ID read: 0x%02X 0x%02X\n", raw[0], raw[1]); uint8_t before = read_reg(REG_CTRL_MEAS); write_reg(REG_CTRL_MEAS, 0x24); // osrs_t x1, osrs_p x1, sleep mode uint8_t after = read_reg(REG_CTRL_MEAS); printf("ctrl_meas: 0x%02X -> wrote 0x24 -> read back 0x%02X\n", before, after); write_reg(REG_CTRL_MEAS, before); // restore the old value } catch (const std::exception& e) { fprintf(stderr, "%s\n", e.what()); return 1; } } |
Build it with g++, and run it without sudo:
|
1 2 |
g++ -std=c++17 -O2 -Wall bmp280_spi.cpp -o bmp280_spi ./bmp280_spi |
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:
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):
|
1 2 |
clk_div = min(DIV_ROUND_UP(200000000, max_speed_hz) + 1, 0xfffe) & 0xfffe; // even, 2 to 65534 SCLK = 200000000 / clk_div; |
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_hz | Divider | Expected SCLK | Measured SCLK |
|---|---|---|---|
| 100000 | 2000 | 100kHz | 100.0kHz |
| 500000 | 400 | 500kHz | 500.0kHz |
| 1000000 | 200 | 1MHz | 1.000MHz |
| 2000000 | 100 | 2MHz | 2.000MHz |
| 4000000 | 50 | 4MHz | 4.000MHz |
| 8000000 | 26 | 7.69MHz | 7.69MHz |
| 12500000 | 16 | 12.5MHz | 12.54MHz |
| 16000000 | 14 | 14.29MHz | 14.29MHz |
| 20000000 | 10 | 20MHz | 20.00MHz |
| 25000000 | 8 | 25MHz | 24.98MHz |
| 32000000 | 8 | 25MHz | 25.00MHz |
| 40000000 | 6 | 33.33MHz | 33.33MHz |
| 50000000 | 4 | 50MHz | 50.00MHz |
| 66666666 | 4 | 50MHz | 50.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_hz | Real SCLK | Bytes Checked | Bit Errors | C++ Throughput |
|---|---|---|---|---|
| 1000000 | 1MHz | 1.3MB | 0 | 125.0kB/s |
| 4000000 | 4MHz | 5.2MB | 0 | 499.7kB/s |
| 10000000 | 10MHz | 5.2MB | 0 | 1,248kB/s |
| 20000000 | 20MHz | 5.2MB | 0 | 2,493kB/s |
| 25000000 | 25MHz | 5.2MB | 0 | 3,115kB/s |
| 40000000 | 33.33MHz | 21MB | 4 (in the first run only) | 4,148kB/s |
| 50000000 | 50MHz | 21MB | 0 | 6,209kB/s |
| 100000000 | 100MHz | 5.2MB | 20,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) | 10MHz | 50MHz |
|---|---|---|
xfer2(), 4096-byte chunks | 1,195kB/s | 5,080kB/s |
xfer3(), one 1MB call | 1,213kB/s | 3,456kB/s |
writebytes2(), one 1MB call (write only) | 1,249kB/s | 3,837kB/s |
xfer2() of 1 byte, time per call | 26.9µs | 22.8µs |
C++ SPI_IOC_MESSAGE, 64KB transfers | 1,248kB/s | 6,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:
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:
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:
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):
|
1 |
sudo modprobe -r spidev && sudo modprobe spidev bufsiz=65536 |
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:
- 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 = 0 | ioctl(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:
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:
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
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'):
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:
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.
