SPI
Clock modes, chip select, multiple devices and throughput.
Fast, simple and full duplex
SPI (serial peripheral interface) is a synchronous serial bus with separate lines for each direction. It is the usual choice for anything that needs speed: flash memory, displays, ADCs, radio transceivers, SD cards. Clock rates of 10 to 50 MHz are common, over 100 MHz for quad-SPI flash.
| Signal | Also called | Direction |
|---|---|---|
| SCK | SCLK, CLK | Controller to peripheral |
| MOSI | COPI, SDO (on the controller) | Controller to peripheral |
| MISO | CIPO, SDI (on the controller) | Peripheral to controller |
| CS | SS, NSS, CE | Controller to peripheral, one per device, usually active low |
There is no addressing, no acknowledgement and no protocol on the wire: the controller asserts one device's CS, clocks bytes out and simultaneously clocks bytes in, then releases CS. Every clock edge moves one bit each way, so every transfer is an exchange: to read a byte, you must send one (usually a dummy 0x00 or 0xFF).
The four modes
Two settings must match the peripheral's datasheet:
- CPOL (clock polarity): the idle level of SCK, 0 or 1.
- CPHA (clock phase): whether data is sampled on the first (0) or second (1) clock edge.
| Mode | CPOL | CPHA | Idle clock | Data sampled on |
|---|---|---|---|---|
| 0 | 0 | 0 | Low | Rising edge |
| 1 | 0 | 1 | Low | Falling edge |
| 2 | 1 | 0 | High | Falling edge |
| 3 | 1 | 1 | High | Rising edge |
Mode 0 is the most common; many devices accept both 0 and 3. A wrong mode often "almost works": data shifted by one bit, or correct at low speed only.
Bit order (MSB first is almost universal) and word size (8 bits, sometimes 16) must also match.
A transfer, bit by bit
This simulation bit-bangs mode 0, MSB first, against a fake peripheral that returns the bitwise inverse of what it receives:
#include <stdio.h>
#include <stdint.h>
static uint8_t periph_shift; /* the peripheral's shift register */
/* One full-duplex byte exchange in SPI mode 0, MSB first. */
static uint8_t spi_transfer(uint8_t out) {
uint8_t in = 0;
for (int bit = 7; bit >= 0; bit--) {
int mosi = (out >> bit) & 1; /* controller sets MOSI while SCK is low */
int miso = (periph_shift >> 7) & 1; /* peripheral has its bit on MISO */
/* rising edge: both sides sample */
in = (uint8_t)((in << 1) | miso);
periph_shift = (uint8_t)((periph_shift << 1) | mosi);
/* falling edge: next bits are set up */
}
return in;
}
int main(void) {
/* CS low */
uint8_t r1 = spi_transfer(0x9F); /* e.g. "read ID" command; reply is junk */
periph_shift = (uint8_t)~periph_shift; /* peripheral prepares its answer */
uint8_t r2 = spi_transfer(0x00); /* dummy byte clocks the answer out */
/* CS high */
printf("sent 0x9F, got 0x%02X during the command\n", r1);
printf("sent 0x00, got 0x%02X (the reply)\n", r2);
return 0;
}
The pattern "send command, then send dummy bytes to read the answer" is how almost every SPI peripheral is read.
Chip select handling
CS frames a transaction. Many devices only latch a command when CS rises, and reset their internal state machine when CS falls, so:
- hold CS low for the whole command plus data, not per byte
- respect the setup and hold times in the datasheet (minimum time from CS low to the first clock, and from the last clock to CS high)
- wait until the SPI peripheral is truly finished (the BSY flag clear, not just "transmit buffer empty") before raising CS, otherwise the last byte is cut off
Hardware-managed NSS on many MCUs toggles CS automatically but is often awkward for multi-byte transactions; most drivers drive CS as a plain GPIO.
Several devices on one bus
SCK, MOSI and MISO are shared; each device gets its own CS. Problems to watch:
- MISO must be tri-stated by every deselected device. A badly behaved device that drives MISO while deselected corrupts reads from the others.
- Different modes or speeds per device: reconfigure the SPI peripheral before each transaction, inside the bus lock.
- RTOS access: protect the bus with a mutex held for the entire transaction, CS included.
- Long traces and many loads reduce the usable clock rate; a 50 MHz SPI across a board-to-board cable rarely works.
Getting throughput
| Technique | Effect |
|---|---|
| Polling per byte | CPU-bound; gaps between bytes |
| Interrupt per byte | Frees the CPU, but interrupt overhead limits rate |
| FIFO (where available) | Fewer interrupts |
| DMA | Back-to-back bytes at full clock rate, no CPU |
| Dual / quad SPI | 2 or 4 data lines for flash: 2 to 4 times the bandwidth |
| Memory-mapped QSPI | External flash appears in the address map; code can execute from it |
For a display or a flash write, DMA with a transfer-complete callback that raises CS is the standard design.
Pitfall: On a full-duplex SPI, transmit-only DMA still fills the receive register with bytes. If nobody reads them, the overrun flag sets, and some peripherals stop until it is cleared. Either run a receive DMA into a dummy buffer or configure a transmit-only mode.
SPI versus I2C
| SPI | I2C | |
|---|---|---|
| Wires | 3 + one CS per device | 2 |
| Speed | Tens of MHz | 0.1 to 1 MHz typical |
| Duplex | Full | Half |
| Addressing | By CS line | 7-bit address on the wire |
| Acknowledgement | None | Every byte |
| Distance | Short, on-board | Short, on-board |
| Good for | Flash, displays, fast ADCs, radios | Many slow sensors with few pins |
Interview question: Data from an SPI sensor is shifted by one bit. What do you check?
Answer: The SPI mode: CPOL and CPHA must match the datasheet, since sampling on the wrong edge produces exactly this symptom. Then bit order and word size, the clock rate against the device maximum (and signal integrity at that rate), and CS timing: whether CS is asserted early enough before the first clock and held for the whole transaction. A logic analyser with an SPI decoder set to the same mode confirms which side is wrong.
Interview question: Several devices share one SPI bus in an RTOS. How do you make access safe?
Answer: Give each device its own chip select and wrap every transaction in a bus mutex, held from CS assertion to CS release, so two tasks never interleave bytes. Inside the lock, reconfigure the SPI mode and clock rate for that device. Wait for the BSY flag before releasing CS. Use DMA with a completion semaphore for long transfers so the task blocks instead of spinning, and ensure every deselected device tri-states MISO.
Build it: know when the scooter has fallen over
This is step 2 of the module project. A motion sensor on SPI tells the tracker how the scooter is lying, so the fleet operator gets an alert when one has been knocked over in the street.
Lab: Read the motion sensor and detect a fall
The sensor is an ST-style accelerometer on SPI1, selected by PA4 (low = selected). The SPI port and chip select helpers are already written (under Register map and definitions). Your job is the sensor's protocol and what the numbers mean.
The protocol: pull chip select low, send a register address (bit 7 set to read), then each further byte reads or writes the next register. Raise chip select at the end.
imu_init()readsWHO_AM_I(register0x0F). If it is not0x6B, the wrong part is fitted or the bus is broken: return false without touching anything else. Otherwise turn the sensor on by writing0x40toCTRL1(0x10), which is 104 readings a second at ±2 g, and return true.imu_read_mg(mg)reads the six bytes fromOUTX_L(0x28) toOUTZ_H(0x2D) in one burst, under a single chip select, so x, y and z come from the same moment. Each axis is a signed 16-bit value, low byte first. At ±2 g, 16384 counts are 1 g: store each as milli-g,raw * 1000 / 16384.scooter_fallen()reads the sensor and returns true when the deck is no longer roughly horizontal: the z axis (straight up through the deck) reads less than 500 mg either way.
Chip select edges appear in the output as gpioa: pin 4 low and high, and every register the sensor stores as imu: write 0x10 = 0x40.
Going deeper
Interview question: How would you update a smartwatch's display smoothly while saving power?
Answer: Send pixel data over SPI by DMA, redraw only the regions that changed, use the display controller's partial update and low-power modes, and keep the frame rate low when nothing animates. Choose the SPI clock as high as the display and wiring allow, and convert graphics to the display's format ahead of time.
Interview question: What is quad SPI memory-mapped mode and why is it useful?
Answer: Quad SPI uses four data lines to read external flash four bits per clock. In memory-mapped mode the controller makes the flash appear in the address space, issuing read commands automatically on each access, so the CPU can read data or even execute code directly from external flash (execute in place), often with caching. It extends a microcontroller's program memory cheaply.
Interview question: How do you handle SPI devices that need different modes on the same bus?
Answer: Reconfigure the SPI peripheral's CPOL, CPHA, clock rate and word size before each transaction, inside the bus lock, while chip select is still high, and keep the clock idle state correct before asserting CS. Wrapping transactions in a function that takes the device's configuration makes it automatic.
Explain it: In your own words, explain why reading from an SPI device requires sending bytes.
Answer: SPI is full duplex and only the controller generates the clock: every clock pulse shifts one bit out on MOSI and one bit in on MISO at the same time. A peripheral can only send data while the controller is clocking, and the controller only clocks while it transmits. So to read N bytes, the controller must send N bytes, usually dummy values such as 0x00 or 0xFF, and the bytes received during those transfers are the device's reply.