Embedded Systems · Embedded Buses
The Shift Register Behind SPI and Why There Are Four Clock Modes
Two shift registers joined by two wires explain SPI completely, including the CPOL and CPHA combinations, the daisy chain, and the consequences of having no acknowledgement.
SPI is usually taught as a list of signals and a table of four modes, and that presentation hides the fact that the interface is a single mechanism with no protocol on top of it. The mechanism is a pair of shift registers, one in the master and one in each slave, connected in a ring by two wires and advanced by a shared clock. Everything else — the mode table, the daisy chain, the absence of addressing — falls out of that picture.
Two registers in a ring
Picture an eight-bit shift register in the master and an eight-bit shift register in the slave. The master’s most significant output bit is wired to the slave’s least significant input. The slave’s most significant output bit is wired back to the master’s least significant input. The two registers share a clock. On each clock edge both registers shift one position, so after eight edges the contents have swapped completely. The master has transmitted one byte and simultaneously received one byte.
This is why SPI is full duplex in the strongest sense: the master cannot transmit without receiving, and it cannot receive without transmitting. A master that only wants to read a sensor must still send something, and the conventional filler is an all-ones byte or an all-zeros byte, chosen so that the slave does not interpret the write as a command. The “dummy byte” is not an artefact of a driver; it is what the ring requires.
The ring also explains the timing requirement. A shift register has a setup time before the clock edge and a hold time after it, so the bit must be stable on the input during a window around the sampling edge. If both ends sample on the same edge that they shift on, the previous bit has not yet arrived. One side must shift on one edge and sample on the other. That single constraint is the entire content of the mode table.
Four modes from two independent choices
Clock polarity, CPOL, decides whether the idle level of the clock is low or high. Clock phase, CPHA, decides whether data is sampled on the first edge of each clock period or the second. Combining the two gives four modes, and every real device specifies one of them in its datasheet.
| Mode | CPOL | CPHA | Idle clock | Bits change on | Bits sampled on |
|---|---|---|---|---|---|
| 0 | 0 | 0 | low | falling | rising |
| 1 | 0 | 1 | low | rising | falling |
| 2 | 1 | 0 | high | rising | falling |
| 3 | 1 | 1 | high | falling | rising |
The pattern is easier to remember than the table. With CPHA equal to zero, the first edge of each clock period samples the bit that is already on the line, and the second edge moves the next bit out. With CPHA equal to one, the first edge moves the next bit out and the second edge samples it. CPOL then only relabels which physical edge counts as first: a clock that idles low leads with a rising edge, one that idles high leads with a falling edge.
Mode 0 and mode 3 are the common ones in sensor and memory datasheets. A mismatch between the two ends is not a clean failure. The master sends a byte, the slave samples the wrong edges, and what comes back is offset by one bit position or is sampled while the line is still moving. A value that looks like a plausible reading but is consistently off by a factor of two, or that changes only every other transfer, is a strong hint that CPHA is wrong; a value that is always all ones or all zeros suggests the slave is not driving the line at all.
Chip select and the absence of addressing
SPI has no address field. Selecting a device is done electrically, by pulling its chip-select input low, and only the selected device is allowed to drive its output line. Every other device on the bus must leave its output in a high-impedance state, or the two outputs fight and the result is undefined.
This is the central economic difference from a two-wire bus. A bus with addressing needs two wires regardless of device count. SPI needs three shared wires — clock, data out, data in — plus one chip-select wire for each device, so a bus with eight slaves needs eleven wires in total. On a board with a handful of peripherals that is fine and fast. On a board with many, or on a connector that leaves the board, the wire count becomes the constraint, and open-drain signalling and arbitration describes the alternative that trades speed for wires.
Chip select is also where most SPI bugs live. The select line must be asserted before the first clock edge and released after the last one, and the required timing is asymmetric: some devices need the select to be low for a minimum period before the first clock, some need a minimum high period between transactions, and some will latch the last byte early if the select rises before the final clock edge has completed. A driver that toggles select per byte rather than per transaction works with a device that treats each byte independently and fails with one that expects a command byte followed by data bytes.
The daisy chain configuration reuses the ring idea. Instead of separate select lines, the master’s output feeds the first slave, the first slave’s output feeds the second, and the last slave’s output returns to the master. All slaves share one select line. The master shifts a stream whose length is the sum of all the slaves’ register widths, and each slave, once its own bits have arrived, passes subsequent bits through. This costs one select wire regardless of device count, at the cost of a transfer length that grows linearly and a fixed order that cannot be skipped.
What the clock rate actually depends on
SPI has no standard maximum clock rate. The rate is whatever both ends can support, and the practical number is set by the round-trip path, not by the wire. The master drives the clock out, the slave sees it after the propagation delay of the trace and the input buffer, drives its data back, and the data must arrive before the master samples on the opposite edge. Half a clock period must therefore accommodate the round trip plus setup time.
This is why the same peripheral works at one rate on a short board and not on a long cable, and why some controllers offer a divide-by-two of the peripheral clock as their maximum. A ribbon cable of tens of centimetres at tens of megahertz behaves as a transmission line, and the reflections described in differential signalling and termination apply to its single-ended signals with no termination to absorb them.
There is also no flow control. The slave cannot tell the master to wait, because there is no handshake line and no acknowledge slot. A slave that needs time between bytes, for instance a flash device during a program operation, can only signal readiness by a separate ready/busy pin or by the master polling a status register. A slave that cannot keep up simply returns stale or zero data, and the master has no way to know.
A short transaction in a typical controller style shows the structure:
static void spi_transfer(const uint8_t *tx, uint8_t *rx, size_t n)
{
cs_assert(); /* one select for the whole transaction */
for (size_t i = 0; i < n; i++) {
uint8_t out = tx ? tx[i] : 0xFF; /* dummy byte keeps the ring turning */
uint8_t in = 0;
for (int b = 7; b >= 0; b--) {
set_mosi((out >> b) & 1u); /* data valid before the sampling edge */
pulse_clock(); /* rising samples, falling shifts */
in = (uint8_t)((in << 1) | (read_miso() & 1u));
}
if (rx) rx[i] = in;
}
cs_release();
}
The loop shows the consequence of full duplex plainly: the received byte is assembled from the same eight clock pulses that send the outgoing byte, and there is no point in the loop where one direction is active and the other is not.
Error detection is left to the application
SPI defines no parity, no checksum, no framing marker, and no timeout. A byte that is corrupted in transit arrives as a valid byte. A slave that is not selected but drives the line anyway produces a wired conflict that may read as either value depending on the drive strengths. A master that generates one clock pulse too many shifts the slave’s register by one bit and every subsequent byte is misaligned for the rest of the transaction, because nothing in the protocol resynchronises.
The usual mitigations are all above the bus. Commands are given a fixed structure so that a misaligned stream is detectable as an invalid command. Registers carry a read-back of the value just written. Critical transfers are repeated and compared. Where the peripheral supports it, a CRC is computed over the payload by both ends. None of these are part of SPI; they are the price of a protocol that chose speed and simplicity over any guarantee.
That choice is defensible for a bus that stays inside one enclosure and connects a handful of devices at short range. The same bus becomes the wrong tool as soon as the wire leaves the board, the device count grows, or more than one master must share the bus, because all three of those cases are exactly what the ring and the chip select cannot express.
References
- Linux kernel documentation: SPI — Linux kernel project
- M68HC11 Reference Manual — Freescale Semiconductor
- AN991: Using the Serial Peripheral Interface to Communicate Between Multiple Microcomputers — Motorola Semiconductor Application Note