Home / Learn Chip Programming / SPI Protocol and Modes
SPI Protocol and Modes
Fast four wire bus for flash, displays, ADCs and radios.
Theory in plain words
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
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.
| Mode | CPOL | CPHA | Idle clock | Sample edge |
|---|---|---|---|---|
| 0 | 0 | 0 | low | rising |
| 1 | 0 | 1 | low | falling |
| 2 | 1 | 0 | high | falling |
| 3 | 1 | 1 | high | rising |
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 17Quick quiz
1. How many wires for SPI with one slave?
SCLK, MOSI, MISO and CS.
2. Common cause of garbage SPI data?
CPOL/CPHA must match the device.
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.