Home / Learn Chip Programming / SPI Protocol and Modes

SPI Protocol and Modes

Fast four wire bus for flash, displays, ADCs and radios.

In shortFast four wire bus for flash, displays, ADCs and radios.

Theory in plain words

SPI transferCS low8 clocks: MOSI out, MISO inrepeat for each byteCS high
SPI transfer

What it is

SPI has SCLK, MOSI, MISO and a chip select per device. Master shifts bits out on MOSI while shifting in on MISO. Modes 0 to 3 define clock polarity (CPOL) and phase (CPHA).

Why we use it

SPI is much faster than I2C (up to tens of MHz) and has no addressing overhead. Wrong mode gives garbage data; that is the most common SPI bug.

How it works

Pull CS low, clock out bytes, read the bytes shifted in, raise CS. Check the device datasheet for the mode and the maximum clock.

Where it is used

  • SD card, W25Q flash, ILI9341 TFT
  • MCP3008 ADC, nRF24 radio
  • Shift registers like 74HC595

SPI shift simulator

Master and slave exchange a byteTry it Yourself

SPI is full duplex: every byte sent also receives a byte. To read a register you send a command then clock out a dummy byte.

ModeCPOLCPHAIdle clockSample edge
000lowrising
101lowfalling
210highfalling
311highrising
Read the JEDEC ID of a W25Q flash
CS_LOW();
spi_xfer(0x9F);                 // command: read JEDEC ID
uint8_t mfg  = spi_xfer(0x00);  // dummy bytes clock the answer in
uint8_t type = spi_xfer(0x00);
uint8_t cap  = spi_xfer(0x00);
CS_HIGH();                      // W25Q64 returns EF 40 17
Tip:Keep wires short, share GND, and add 22 to 100 ohm series resistors on fast clock lines to reduce ringing.

Quick quiz

1. How many wires for SPI with one slave?

2. Common cause of garbage SPI data?

Common questions

How many wires for SPI with one slave?

4. SCLK, MOSI, MISO and CS.

Common cause of garbage SPI data?

Wrong SPI mode. CPOL/CPHA must match the device.