Explain CPOL and CPHA. What are the four SPI modes, and how do you choose the right one?
CPOL (Clock Polarity) and CPHA (Clock Phase) define when data is driven onto the bus and when it is sampled. Getting them wrong is the number-one cause of "SPI isn't working" bugs.
CPOL sets the clock's idle state: CPOL=0 means SCK idles low; CPOL=1 means SCK idles high. CPHA determines which clock edge is used for sampling data: CPHA=0 means data is sampled on the first (leading) edge and shifted out on the second (trailing) edge; CPHA=1 means data is sampled on the second (trailing) edge and shifted out on the first (leading) edge.
The four combinations yield four SPI modes:
| Mode | CPOL | CPHA | SCK Idle | Data Sampled On | Data Shifted On |
|---|---|---|---|---|---|
| 0 | 0 | 0 | Low | Rising edge | Falling edge |
| 1 | 0 | 1 | Low | Falling edge | Rising edge |
| 2 | 1 | 0 | High | Falling edge | Rising edge |
| 3 | 1 | 1 | High | Rising edge | Falling edge |
You choose the mode by consulting the slave device's datasheet — it specifies which mode(s) the device supports. Most sensors and flash chips use Mode 0 or Mode 3 (sample on rising edge). The master must be configured to match. If you have multiple slaves on the same bus that require different modes, you must reconfigure the master's SPI peripheral each time you switch between them (before asserting the next CS).
A common interview trap: candidates memorize the table but cannot explain why mode matters. The answer is setup and hold time — data must be stable on the bus for a minimum time before and after the sample edge. If the master drives data on the same edge it samples, the slave sees data that is still transitioning, and communication fails.
Source: SPI Q&A
