Sub topic 1
What SPI is and where it is used
Prerequisites
This chapter assumes you can write a basic Arduino sketch with setup() and loop(), use pinMode() and digitalWrite(), read a simple wiring diagram, and convert between binary and hexadecimal.
What SPI is and where it is used
SPI (Serial Peripheral Interface) is a synchronous serial bus. A controller, usually a microcontroller such as an Arduino, exchanges data with one or more peripherals over a few shared wires. Peripherals that commonly use SPI include SD cards, color displays, flash memory chips, and fast sensors.
The four signals
SPI uses four signals:
- SCLK: the clock. The controller generates it, and every bit moves on a clock edge.
- MOSI: controller out, peripheral in. Data flows from the controller to the peripheral.
- MISO: controller in, peripheral out. Data flows from the peripheral to the controller.
- CS (chip select): one line per peripheral. The controller pulls it LOW to select that device.
How a transfer exchanges bits in both directions
SPI is full duplex. Each clock pulse shifts one bit out on MOSI and one bit in on MISO, so sending one byte also receives one byte.
Chip select: starting and ending a transfer
Chip select is active LOW. The peripheral ignores the bus while CS is HIGH, so several peripherals can share MOSI, MISO, and SCLK.
Clock polarity and phase: the four SPI modes
Two settings define the mode. CPOL sets the idle level of the clock. CPHA sets which edge the device samples data on.
| Mode | CPOL | CPHA | Clock idle level | 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 |
Always take the mode from the peripheral's datasheet timing diagram. A wrong mode usually returns garbage bytes rather than an error.
Exercise
Exercise
A datasheet says the clock idles LOW and the peripheral samples data on the rising edge. Which SPI mode is this?
Show answer
Mode 0 (CPOL = 0, CPHA = 0). An idle-low clock means CPOL is 0. Sampling on the rising edge, which is the leading edge when the clock idles low, means CPHA is 0.