← all lessons
Single-Ended Buses · SPI & I²C · #33 of 48

SPI & Its Four Modes

CPOL, CPHA, CS Framing and Clock Integrity

A benchtop logic analyzer with a wide screen and rows of input channels.
A logic analyzer captures many digital lines at once. On a four-wire SPI link it is the tool that shows you which clock edge the data actually lands on. · Daichinger, Public domain

The joint encoder on the robot hand’s index finger reports its angle over four wires, and on the very first power-up it reads back pure nonsense: the finger thinks it is at 47 degrees when you can plainly see it sitting at zero, and the number jitters with every twitch of the motor. You scope all four wires. The clock is clean. The chip-select drops and rises right where it should. Data is moving on both data lines. Every wire is doing exactly what the datasheet drew, and the number is still garbage.

The wires are right. The agreement is wrong.

SPI is the simplest fast bus in the building, and that simplicity hides a trap: the master and the device must agree, ahead of time, on exactly which clock edge means “the data is valid now.” There is no handshake to negotiate it and no acknowledge bit to catch a mismatch. Get that agreement wrong and you read perfect-looking edges that land on the wrong half of every bit. The whole lesson turns on one ordering idea: a byte on SPI is only correct when both ends sample it on the same edge, and that edge is fixed by two bits called CPOL and CPHA before the first clock ever ticks.

By the end, you can

  1. Name the four SPI signals (SCLK, MOSI/COPI, MISO/CIPO, CS) and state what each does
  2. Define CPOL and CPHA and map the four (CPOL, CPHA) pairs to SPI modes 0-3
  3. Diagnose a same-wires, wrong-data fault as a mode mismatch rather than a wiring error
  4. Explain CS framing, the MISO high-Z requirement, and why fast SCLK needs series source termination

Intuition first

Picture two people clapping in time to pass a bucket back and forth. The clap is the clock: it is the shared metronome that says “now.” But a clap has two events buried in it. There is the moment the hands start moving (the swing) and the moment they meet (the strike). If one person hands over the bucket on the swing and the other reaches for it on the strike, the handoff still happens on every clap, smoothly, looking perfectly coordinated, and the bucket still gets dropped half the time because they are acting on different halves of the same beat.

SPI is exactly this. SCLK is the shared clap. CPHA decides whether you act on the first edge of each clock pulse or the second one. CPOL decides which way the clock swings to begin with, whether it rests low and pulses high or rests high and pulses low. Both ends are clapping in time. If they disagree about which edge is the strike, the data lands one half-bit off, and you get clean wires with garbage values. That is the entire failure in the Hook, and there is no error bit to warn you about it.

So before any byte crosses the bus, both sides have to settle two yes-or-no questions: which level does the clock idle at, and do we latch the data on the leading edge of each pulse or the trailing one. Two bits, four combinations, four modes.

The four signals

SPI is a four-wire, synchronous, full-duplex bus, almost always with a single master. Synchronous means the master ships a clock alongside the data, so neither end needs a precise oscillator the way an asynchronous UART does. Full-duplex means data flows both directions at once, on two separate wires, one bit per clock edge in each direction.

SignalAlso calledDriven byJob
SCLKSCK, CLKmasterthe shared clock, the metronome
MOSICOPI, SDO/SDImastermaster out, device in
MISOCIPO, SDI/SDOdevicedevice out, master in
CSSS, CE, nSSmasteractive-low select for one device

The newer COPI (“controller out, peripheral in”) and CIPO (“controller in, peripheral out”) names mean exactly the same wires as MOSI and MISO. They are worth knowing because they kill the directional confusion: COPI always carries data out of the controller no matter which chip you are staring at, whereas “MOSI on the master connects to MOSI on the device” trips people up every single time.

Internally each end is a shift register, and the two registers are wired nose-to-tail into one big loop. On each clock edge the master shoves one bit out of MOSI while the device shoves one bit out of MISO, and on the matching edge each side latches the bit that arrived. Clock eight times and the two registers have swapped their full contents. That is why SPI is full-duplex for free: a read and a write are the same eight clocks. If you only care about one direction, the other direction still happens, and you simply ignore the bits you did not want.

CPOL, CPHA, and the four modes

Two configuration bits set the timing, and the master must program both before it starts clocking. They are independent, so there are 2×2=42 \times 2 = 4 combinations.

CPOL (clock polarity) is the level the clock sits at when idle, between transactions.

CPOL=0    SCLK idles lowCPOL=1    SCLK idles high\text{CPOL} = 0 \;\Rightarrow\; \text{SCLK idles low} \qquad \text{CPOL} = 1 \;\Rightarrow\; \text{SCLK idles high}

CPHA (clock phase) decides which of the two edges in each clock pulse is the sampling edge, where a receiver latches the bit. The other edge is when the transmitter changes the bit. With CPHA = 0 you sample on the leading (first) edge of each pulse and shift on the trailing edge. With CPHA = 1 you shift on the leading edge and sample on the trailing edge.

The mode number packs them with CPOL as the high bit and CPHA as the low bit, so the mode is just the two-bit binary number (CPOL,CPHA)(\text{CPOL}, \text{CPHA}):

ModeCPOLCPHAClock idlesData sampled on
000lowrising SCLK (leading)
101lowfalling SCLK (trailing)
210highfalling SCLK (leading)
311highrising SCLK (trailing)

Read the “sampled on” column carefully. In modes 0 and 3 the sampling edge is rising; in modes 1 and 2 it is falling. CPOL flipped the idle level, which swapped which physical direction the “leading” edge points, so a rising-sample mode 0 and a rising-sample mode 3 are not the same thing even though both sample on a rising edge, because the data is shifted out at different times relative to that edge.

Here is mode 0 (the most common one, the default for most parts) sketched out. Idle low, CS frames the byte, and the receiver latches on each rising edge:

        assert                                            deassert
  CS  ‾‾‾|________________________________________________|‾‾‾‾
         |   b7    b6    b5    b4    b3    b2    b1    b0   |
SCLK ____|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|_|‾|___    (idle low)
          ^     ^     ^     ^     ^     ^     ^     ^
          |     |     |     |     |     |     |     |
        sample on each RISING edge (CPHA=0, leading)
 MOSI  <data is set up just before each rising edge, held through it>

Now the punchline, the fact that the Hook was built around: the master and the device must use the same mode, or the data is garbage even though the wires are perfect. There is no negotiation. If your encoder datasheet says mode 1 and your driver brought the bus up in mode 0, every bit is sampled half a clock too early, and you read a plausible, stable, completely wrong number. No flag is raised, because to SPI nothing went wrong: the master clocked, the device shifted, bits were latched. They were simply latched on the wrong edge.

CS framing, high-Z, and clock integrity

Three more facts separate a bus that works on the bench from one that works in the field.

CS framing. Chip-select is active-low, and it does not just pick a device, it frames the transaction. The rule is strict: assert CS (drive it low) before the first clock edge, and deassert it (release it high) after the last clock edge. Many devices treat the falling edge of CS as “start of a new word, reset my bit counter,” and the rising edge as “word complete, act on it.” Clock a device with CS already low from a previous transfer and it may keep counting bits into the wrong field. Drop CS in the middle of a word and you truncate the command. CS is the envelope around the bits, and a torn envelope loses the letter.

MISO must go high-Z. When a device is not selected, its MISO output must release to high-impedance, electrically disconnecting itself from the wire. This is what lets several devices share one MISO line: each one ties up that wire only while its own CS is low, and floats off it otherwise. A device that drives MISO hard even when deselected will fight every other device on the bus the moment two CS lines are low at once, or fight nothing but still hold the line at a stuck level. If a part lacks a true tri-state output, you bolt an external tri-state buffer onto its MISO and gate that buffer with the device’s CS.

Clock integrity. SPI uses push-pull drivers, not the open-drain wired-AND of I²C, so it can run fast, tens of megahertz and up. But a fast push-pull edge slamming into a PCB trace is a step into a transmission line, and the trace rings: the edge overshoots, dips back, and rattles before it settles. Ringing on SCLK is the dangerous one. A receiver can read a single ring crossing as an extra clock edge and shift one bit too many, corrupting every word after it. The cure is series source termination: a small resistor (often tens of ohms, sized to roughly match the trace impedance minus the driver’s own output resistance) placed at the driver end of the line. It softens the launched edge so the reflection comes home gently instead of crashing.

One quiet gift of SPI’s electrical style: it is single-ended and ground-referenced. Every signal is one wire measured against the board’s shared ground, not a differential pair like CAN. That means an ordinary passive scope probe, ground clip on the board ground, tip on the signal, reads SPI directly and honestly. You do not need a differential probe or any special front end to watch the whole bus, which is exactly why SPI is a pleasure to debug compared to the differential buses earlier in this module.

An SPI joint encoder is wired correctly: SCLK, MOSI, MISO, and CS all scope clean and toggle where the datasheet says they should. The master reads a stable but clearly wrong angle. What is the most likely cause?

Why must a deselected SPI device drive its MISO pin to high-impedance (tri-state)?

Lab: confirm the mode before you trust the bytes

On the bench, bring up a new SPI device in this order. First, open both datasheets and write down the device’s required mode as a (CPOL, CPHA) pair, then set your master to exactly that mode in software before the first transfer. Second, put a scope or logic analyzer on all four wires and check CS framing: CS must fall before the first SCLK edge and rise after the last, with the right number of edges in between. Third, read the device’s known fixed register (most parts have a “who am I” or a constant manufacturer ID) and compare it byte-for-byte against the datasheet value. If that constant comes back wrong but stable, stop and re-check CPOL/CPHA: you are sampling on the wrong edge. If it comes back jittery or intermittent, look at SCLK for ringing and add or tune the series source resistor at the master. Only once the known constant reads correct do you trust any live data the device sends.

The circular shift register, daisy chains, and where the half-bit error physically comes from

The two shift registers, one in the master and one in the device, are not just a metaphor. They are wired into a literal ring: the master’s serial output feeds the device’s serial input, and the device’s serial output feeds the master’s serial input. Together they form one circular buffer of, say, sixteen bits split eight-and-eight. Each clock edge rotates the whole ring by one position. After a full word, the two halves have exchanged places. This is why SPI has no concept of a separate “read command” and “write command” at the wire level: every transfer is a rotation, and reading is just choosing to keep what rotated in while writing is choosing to send what rotates out. The protocol on top (a command byte, an address, a payload) is a convention each chip invents, because the bus itself only knows how to rotate bits.

You can extend the ring. In a daisy-chain topology the first device’s MISO feeds the second device’s MOSI, and so on, with one CS shared by the whole string. The chain becomes a single long shift register, and you clock enough bits to push a word through every link. This is how a stack of 74xx595 output shift registers turns three SPI wires into dozens of outputs, and how 74xx165 input registers read dozens of switches back. The alternative, the usual one, is the multidrop bus: one shared SCLK and MOSI, a shared MISO, and a separate CS per device so exactly one MISO driver is ever active. Both topologies lean on the same tri-state discipline.

Now the physics of the half-bit error. Define the clock period as TT. A receiver needs the data line to be stable for a setup time tsut_{su} before the sampling edge and a hold time tht_h after it:

tsu+th    T2t_{su} + t_h \;\le\; \frac{T}{2}

is the budget the half-cycle gives you. The transmitter changes MOSI on one edge and the receiver latches it on the other edge of that pulse, half a period later, so in the correct mode the data has a full T/2T/2 to settle and is rock-stable when sampled. Flip CPHA and you have told the receiver to latch on the same edge the transmitter is using to change the data. Now the receiver samples a bit that is in the act of transitioning, or it samples the previous bit that has not yet been replaced. Either way the captured word is rotated by one bit position and reads as a stable wrong value, not as noise, because nothing is actually metastable on the clean edges, you are simply reading the wrong bit on purpose. Flip CPOL instead and the leading and trailing edges swap physical direction, which is why mode 0 and mode 2 both sample on the “leading” edge yet land on opposite physical slopes. The four modes are the four ways to answer “which edge, which slope,” and the only correct answer is the one printed in the device’s datasheet.

One last subtlety the original specification allows: in full duplex a master may even transmit in one mode and receive in another, since MOSI and MISO are independent wires sampled at independent points in the half-cycle. Most off-the-shelf parts never use this, but it explains why some datasheets quote a different edge for the device’s output than for its input. When in doubt, trust the timing diagram over the prose.

Grounded in Wikipedia: “Serial Peripheral Interface” (CC BY-SA). The authoritative mode-table mapping (CPOL as the high bit, CPHA as the low bit, and the resulting modes 0-3) and the tri-state MISO requirement follow the course’s authoritative facts, which match that article.

Key takeaways

  • SPI is a four-wire, synchronous, full-duplex, single-master bus: SCLK, MOSI (COPI), MISO (CIPO), and active-low CS.
  • Two bits set the timing: CPOL is the clock's idle level, CPHA is which edge samples. Together they make modes 0-3.
  • Master and device must use the same mode, or you read a stable-but-wrong value with perfectly clean wires and no error flag.
  • CS frames the byte: assert before the first clock, deassert after the last; a torn frame corrupts the word.
  • Unselected devices must drive MISO to high-Z so the line can be shared without contention.
  • Fast push-pull SCLK rings; add a series source resistor at the driver. SPI is single-ended, so a passive probe reads it directly.
Practice 1 warm-up

A sensor datasheet says it operates with the clock idle high and data sampled on the trailing edge of each clock pulse. Give the CPOL bit, the CPHA bit, and the SPI mode number.

Show worked solution

Clock idle high means CPOL=1\text{CPOL} = 1. “Sampled on the trailing edge” means the leading edge is used to shift and the trailing edge to sample, which is CPHA=1\text{CPHA} = 1. Packing CPOL as the high bit and CPHA as the low bit gives the binary number (1,1)=112=3(1, 1) = 11_2 = 3. So it is mode 3: CPOL 1, CPHA 1. (Consistency check against the table: mode 3 idles high and samples on the rising edge, which for an idle-high clock is the trailing edge of each high-going pulse. It matches.)

Practice 2 core

You bring up the robot hand’s joint encoder. The master is configured for SPI mode 0. The scope shows a clean idle-low clock, CS framing the eight bits correctly, and clean data on MISO, yet the angle reads a steady, wrong value. A glance at the encoder datasheet shows it requires mode 1. Explain, in terms of sampling edges, why the value is wrong but stable, and state the one-line fix.

Show worked solution

The encoder (mode 1, CPHA 1) changes its MISO data on the leading rising edge of each clock pulse and holds it stable to be sampled on the trailing falling edge. The master, in mode 0 (CPHA 0), instead samples on the leading rising edge, the very edge the encoder is using to change the bit. So the master latches either a transitioning bit or the previous bit that has not yet updated. The captured word comes out rotated by one bit position: a definite, repeatable, wrong number, not noise, because the clean edges are never metastable, the master is just reading the wrong bit deliberately. The fix is one line of configuration: set the master to mode 1 so it samples on the trailing edge the encoder intended. No rewiring, no resistor; the wires were always right.

Practice 3 stretch

A flash chip and the joint encoder share one SPI bus in multidrop: shared SCLK, shared MOSI, shared MISO, and a separate CS to each. You raise the clock to 24 MHz to speed up a firmware read. The encoder, which read fine at 1 MHz, now occasionally returns a value that is off by exactly one bit, and the error gets worse when you flex the ribbon cable. Walk through what is physically happening and give two fixes.

Show worked solution

At 24 MHz the SCLK edges are fast enough that the push-pull driver launches a step into the trace as a transmission line. With the longer, higher-impedance path through a flexing ribbon, the impedance is poorly controlled and mismatched, so each edge reflects and rings. A ring on SCLK that crosses the logic threshold a second time is read by the encoder as an extra clock edge: it shifts one bit too many, and every subsequent bit in the word is rotated, giving the off-by-one read. Flexing the cable changes the impedance and the reflection timing, so the error comes and goes, which is the giveaway that this is a signal-integrity fault, not a mode mismatch (a mode error would be constant). Two fixes: (1) add a series source termination resistor at the master’s SCLK pin (tens of ohms, sized near the trace impedance minus the driver’s output resistance) to soften the launched edge so the reflection returns gently and never re-crosses the threshold; (2) slow the clock for the encoder, or route a cleaner, shorter, controlled-impedance path for SCLK instead of a flexing ribbon. Keeping the high clock only for the flash and dropping to a safe rate for the encoder also works, since SPI lets the master pick a frequency per device.

Every wire was right. The clock was clean, the select was crisp, the data marched across both lines exactly as the datasheets drew them. What was wrong was an agreement, two bits deep, about which edge of a shared heartbeat means now. Get that agreement right and SPI is the fastest, friendliest bus on the board. Get it wrong and you can stare at perfect waveforms all afternoon while the finger insists it is somewhere it is not.

full glossary →