Chapters

32 SPI Protocol

networking-core
wired
comm
spi

A controller reads an accelerometer correctly until a display is added to the same serial bus. The new peripheral changes more than the wire count: each transaction needs the correct timing mode and a single selected return-line driver. A known register read makes that contract testable.

32.1 Start With Speed and Selection

Freeze the Timing Contract Before Wiring

Picture a controller reading a motion part that works after power-up but returns shifted values after a restart. The wires are connected, yet the two parts disagree about when a bit is valid and which byte begins the record.

Serial Peripheral Interface (SPI) is a short wired link in which a controller supplies a clock and selects one connected part at a time. A protocol is the agreed order and meaning of that exchange. An analog-to-digital converter is a part that turns a measured voltage into a number; it is often shortened to ADC. Write the clock limit, idle state, sampling edge, bit order, word length, select timing, and reply format before coding.

Test the slowest safe clock first. Read a known register, repeat the transfer, restart each side, and capture the wires when the result changes. Add a second part and prove that an idle device does not drive the shared return line.

One clean bench trace does not cover cable length, noise, or every vendor detail. The deeper sections explain transfer timing, shared-bus faults, and evidence needed to raise speed without losing the contract.

SPI trades extra wires for direct, fast transfers. A controller provides the clock, chooses one device with a select line, and shifts bits in both directions with little protocol overhead.

That makes SPI attractive for displays, radios, memory, and fast sensors, but the design still needs evidence: clock mode, maximum rate, chip-select timing, wiring length, and whether each peripheral can share the bus safely.

32.2 Overview: SPI Trades Wires For Deterministic Transfers

SPI is a short-distance synchronous serial bus for connecting a controller to board-level peripherals such as displays, ADCs, flash memory, radio modules, and sensors. The controller supplies the clock, selects exactly one peripheral with a chip-select line, and shifts data over MOSI and MISO at the same time.

The design trade is simple: SPI avoids addressing overhead and open-drain pull-up limits, but it spends pins. Shared SCLK, MOSI, and MISO lines can serve several peripherals, yet each independently selected peripheral usually needs its own CS line and its own timing contract.

That makes SPI attractive when the product needs predictable bursts of data rather than a self-describing network. A display controller can stream pixels, an external flash chip can clock blocks of bytes, and an ADC can return samples with tight timing because the controller owns the transaction cadence. The same explicitness is also the risk: if firmware asserts the wrong CS, uses the wrong clock phase, clocks too fast for the layout, or assumes a device releases MISO when it does not, there is no bus-level address scan or ACK layer to explain the mistake.

The overview decision is therefore a board-level fit decision. SPI is usually a good match inside one PCB, between stacked boards, or across a very short harness inside the same enclosure. It is weaker as a field cable or shared installation bus because signal integrity, grounding, connector stubs, and device-count wiring become the dominant constraints. For longer or noisier boundaries, a local SPI peripheral should normally sit behind a microcontroller, gateway, or transceiver that exposes CAN, RS-485, Ethernet, or a wireless interface to the outside world.

Before overview: spi trades wires for deterministic transfers, inspect Figure 32.1: SPI Signal Timing must be considered with SS. That visual pairing grounds mosi carries controller-to-peripheral bits, miso carries peripheral-to-controller bits, sclk times the transfer, and cs frames the selected device in named evidence.

SPI signal timing compares high and low SS, MOSI, MISO and SCK traces. Bits received in order are 11010010.
Figure 32.1: MOSI carries controller-to-peripheral bits, MISO carries peripheral-to-controller bits, SCLK times the transfer, and CS frames the selected device.

Use SS to test SPI Signal Timing in the diagram at Figure 32.1. Then inspect MOSI as the final qualifier on mosi carries controller-to-peripheral bits, miso carries peripheral-to-controller bits, sclk times the transfer, and cs frames the selected device. That sequence keeps overview: spi trades wires for deterministic transfers tied to what is visibly labelled.

Synchronous

The controller clock defines when each bit is launched and sampled. Without the correct clock mode, the peripheral can read every bit on the wrong edge.

Full Duplex

Data shifts in both directions on the same clock stream. Some devices use only one direction, but the bus still clocks both paths.

Chip Select

CS is the transaction boundary. The selected peripheral drives or listens; the others should ignore the clocks and release the shared return line.

The next claim about overview: spi trades wires for deterministic transfers depends on Figure 32.2. Its diagram makes SPI Bus Architecture with Multiple Slaves and CS1 explicit within adding peripherals usually adds chip-select wiring and firmware bookkeeping, not bus addresses.

An SPI bus master MCU connects to slave 1, slave 2 and slave 3 over shared MOSI, MISO and SCK clock. CS1, CS2 and CS3 select the individual slaves.
Figure 32.2: Adding peripherals usually adds chip-select wiring and firmware bookkeeping, not bus addresses.

Locate SPI Bus Architecture with Multiple Slaves on Figure 32.2 before checking CS1. The visual’s third anchor, CS2, completes adding peripherals usually adds chip-select wiring and firmware bookkeeping, not bus addresses. Carry SPI Bus Architecture with Multiple Slaves into overview: spi trades wires for deterministic transfers; use CS2 as its limiting condition.

Selection rule: choose SPI when the peripheral needs predictable short-board transfers and the design can afford the pins, routing, and per-device chip-select discipline. Do not choose it only because it is faster on a datasheet; choose it when the board, firmware, and validation plan can preserve the timing margin that the speed requires.

32.3 Practitioner: Treat Each Peripheral As A Timing Contract

An SPI design is not complete when the four signal names are wired. Each peripheral datasheet defines clock mode, maximum clock rate, bit order, command framing, CS timing, bus idle behavior, and whether MISO is released when the device is not selected. Capture those terms before the board is routed and before firmware is written.

Use a per-device contract, not a single bus note. A microSD card, display controller, radio transceiver, and ADC can all share the same SPI controller while needing different clock rates, modes, setup times, and command sequences. The driver should configure those fields at the transaction boundary, and the schematic should make it obvious which GPIO owns each chip select. If an RTOS, DMA engine, or interrupt handler can start transfers from multiple tasks, add a bus lock and record who is allowed to change mode or speed.

Inspect Figure 32.3 before this decision: SPI Clock Mechanism must be judged beside Clock Polarity (CPOL) and Clock Phase (CPHA) Configuration. Together SPI Clock Mechanism and Clock Polarity (CPOL) and Clock Phase (CPHA) Configuration bound this claim.

An SPI mode table compares clock starting level and receive edge for modes 0–3. Master and slave must use the same mode for communication.
Figure 32.3: CPOL and CPHA decide the idle clock level and which edge samples data. A mode mismatch can corrupt every byte while the wiring looks correct.

SPI Clock Mechanism begins the diagram in Figure 32.3; locate SPI Clock Mechanism, compare Clock Polarity (CPOL) and Clock Phase (CPHA) Configuration, and verify Mode. SPI Clock Mechanism states the starting condition; Clock Polarity (CPOL) and Clock Phase (CPHA) Configuration supplies its counterpart; Mode limits the conclusion; retain its labelled boundary.

Those four clock modes have datasheet numbers, not just polarity/phase jargon, and it is worth naming them because most peripheral datasheets specify "Mode 2" or similar rather than spelling out CPOL and CPHA. The four combinations of the idle clock level (CPOL) and the sampling edge (CPHA) are:

SPI clock modes: CPOL sets the idle clock level, CPHA sets which edge is used to sample each bit
ModeCPOLCPHAClock idle levelBit sampled on
000LowRising edge
101LowFalling edge
210HighFalling edge
311HighRising edge

Mode 0 is the most common default. Because the four modes differ by only two bits, a peripheral wired one mode away from its datasheet still clocks bytes in and out -- it just samples every bit on the wrong edge, producing the shifted or corrupted bytes this section's knowledge check describes rather than an obvious no-response failure. In an 8-bit Mode 0 transfer, SS (also called CS on this chapter's other diagrams) drops low for the whole byte, SCLK pulses eight times, and each bit is exchanged MSB-first on MOSI and MISO together before SS releases.

Record Field
What To Capture
Why It Matters
Failure Symptom
Mode
CPOL, CPHA, bit order, word length
Defines which clock edge launches and samples each bit.
Shifted, repeated, or seemingly random register values.
Chip select
Active level, setup time, hold time, deselect gap, shared-device rule
Frames command boundaries and prevents two peripherals from driving MISO together.
No response, response from the wrong device, or bus contention.
Clock rate
Maximum SCLK for this device, board length, load, and voltage domain
A rate that works on a bench wire may fail on a longer route or production board.
Intermittent reads, display artifacts, CRC failures, or temperature-sensitive errors.
Transaction
Command bytes, dummy clocks, read/write bit, address length, response length
Many devices need extra clocks before valid data appears on MISO.
First byte wrong, off-by-one reads, or stale data after a command.
Ownership
Driver owner, bus lock, DMA use, interrupt constraints, and allowed reconfiguration points
Prevents two firmware paths from changing mode or asserting chip select at the same time.
Rare corruption under load, failures during display refresh, or reads broken by another task.

Inspect Figure 32.4 before this decision: SPI Protocol: Full-Duplex Communication must be judged beside SPI Master (ESP32). Together SPI Protocol: Full-Duplex Communication and SPI Master (ESP32) bound this claim.

An ESP32 SPI master connects MOSI, MISO, SCK and CS to an SD card slave. The master generates the clock; the slave is active when CS is low.
Figure 32.4: Review the transaction as a sequence, not just as signal names: select, command, dummy or address phase, data, then deselect.

SPI Protocol: Full-Duplex Communication begins the diagram in Figure 32.4; locate SPI Protocol: Full-Duplex Communication, compare SPI Master (ESP32), and verify MOSI (GPIO 23). SPI Protocol: Full-Duplex Communication states the starting condition; SPI Master (ESP32) supplies its counterpart; MOSI (GPIO 23) limits the conclusion; retain its labelled boundary.

Bring-up habit: validate one peripheral at a time at a conservative clock rate, capture SCLK/MOSI/MISO/CS on a logic analyzer, then raise speed only after mode, framing, and release behavior are proven. Keep one capture for a known-good register read and one for a failed or not-ready response, because those traces become the reference when the same driver later moves to the production board.

32.4 Under The Hood: The Bus Is Fast Because It Is Simple

SPI does not define a universal packet format, address field, arbitration scheme, acknowledgement, or error recovery method. That simplicity is why transfers can be efficient on a PCB, but it also means the application must define the safety rails: retries, status checks, CRC use when available, and what happens after a failed transaction.

Electrical details matter. The controller drives SCLK and MOSI, the selected peripheral drives MISO, and all devices share ground and compatible voltage levels. Long traces, weak return paths, too many stubs, or multiple peripherals driving MISO can create failures that look like firmware bugs.

The clock edge is the contract between digital logic and the physical route. CPOL defines the idle clock level; CPHA defines which edge captures the bit. At low speed with short wires, the wrong mode may still produce recognizable but shifted data. At higher speed, propagation delay, edge rate, ringing, crosstalk, and setup/hold margin decide whether a receiver samples the intended bit. That is why SPI speed should be validated on the final routing, not only on a development jumper.

Failure handling is also device-specific. Some flash memories expose status bits while an erase is in progress, some sensors require dummy clocks before valid data, some radios need an interrupt or ready pin before reading a FIFO, and some devices add CRC fields that firmware must actually check. Without those guards, a transfer can return bytes that are electrically valid but semantically stale, misaligned, or from the wrong command phase.

Pause at Figure 32.5 before carrying under the hood: the bus is fast because it is simple forward. Its visual vocabulary joins SPI Interface to Serial Peripheral Interface • Full Duplex • High Speed, which frames the digital protocol assumes a clean electrical interface: compatible levels, a controlled return path, and only one selected miso driver.

An SPI master shares MOSI, MISO and clock with an ADC sensor and flash memory. Separate SS0 and SS1 lines select slaves for full-duplex communication.
Figure 32.5: The digital protocol assumes a clean electrical interface: compatible levels, a controlled return path, and only one selected MISO driver.

Trace the visual from SPI Interface to Serial Peripheral Interface • Full Duplex • High Speed in Figure 32.5; verify MASTER before concluding. Together those labels make the digital protocol assumes a clean electrical interface: compatible levels, a controlled return path, and only one selected miso driver testable. Apply their boundary when working through under the hood: the bus is fast because it is simple.

No Bus Arbitration

The controller owns the clock and selection. If two peripherals are selected together, the bus can produce invalid data or electrical contention on MISO. Firmware and board design must make simultaneous CS assertion observable and unlikely.

No Standard ACK

Many SPI transfers do not include an acknowledgement. Use device status registers, ready pins, CRC fields, or known-response reads when the device supports them, and log enough context to tell a protocol error from an electrical one.

Short Physical Reach

SPI is strongest inside one board or enclosure. For off-board wiring, reduce speed, control grounding, avoid long stubs, and consider a protocol or transceiver intended for cable runs.

The visual evidence for under the hood: the bus is fast because it is simple sits in Figure 32.6. Find Alternative view beside IoT Platform before interpreting spi is one member of the serial toolkit. it is a good board-level peripheral bus, not a replacement for every wired interface.

An alternative IoT platform view has partial text about each serial protocol excelling in different uses and a Module A label.
Figure 32.6: SPI is one member of the serial toolkit. It is a good board-level peripheral bus, not a replacement for every wired interface.

Begin Figure 32.6 with Alternative view, then distinguish IoT Platform and Each serial. The diagram separates Alternative view from IoT Platform within spi is one member of the serial toolkit. it is a good board-level peripheral bus, not a replacement for every wired interface. Keep both distinctions explicit in under the hood: the bus is fast because it is simple.

Ground under the hood: the bus is fast because it is simple with the visual at Figure 32.7. Start from Wired Protocol Selection Decision Flowchart, but keep Need full visible while evaluating protocol selection should start from distance, device count, data rate, reliability, and available pins rather than from habit.

Wired protocol selection flow comparing SPI, I2C, UART, RS-485, and CAN by speed, distance, device count, and reliability needs.
Figure 32.7: Protocol selection should start from distance, device count, data rate, reliability, and available pins rather than from habit.

Figure 32.7 places Wired Protocol Selection Decision Flowchart alongside Need full. Treat duplex? as the diagram qualifier for protocol selection should start from distance, device count, data rate, reliability, and available pins rather than from habit. That labelled limit reconnects the visual to under the hood: the bus is fast because it is simple.

Release rule: an SPI interface is ready when the timing mode, chip-select map, transaction framing, speed limit, electrical assumptions, ownership rules, and diagnostic readback are all recorded and tested on the target hardware. A useful release record includes the final SCLK rate, a logic-analyzer trace of a known register read, a MISO-release check with other peripherals deselected, and the fallback behavior when the expected status or CRC is not returned.

32.5 Clock a Register Read after Selecting the Right Peripheral

Assume a particular sensor requires one command byte followed by two data bytes under one asserted chip-select interval. The controller must provide 3 × 8 = 24 clock cycles. At 2 MHz, the ideal shift time is 24 divided by 2,000,000 = 12 microseconds. Select setup, hold and software gaps add to that time. This is an illustrative peripheral transaction, not a format imposed by SPI itself.

Full-duplex shifting means bits travel both ways during each clock cycle. The received byte during the command phase may be dummy data under this sensor’s contract. The useful two-byte result begins only afterward. A driver that treats all three received bytes as measurements can create an offset error while the electrical trace remains perfectly regular.

Read Figure 32.1 from select through MOSI, MISO and clock. Then use Figure 32.3 to check the idle level and sampling edge. A matching clock frequency is insufficient if the controller samples while the peripheral is changing the signal.

Predict what happens when the display’s driver leaves the bus in a different mode. The next sensor read needs to restore its timing contract before asserting select. Next, hold both chip-select lines active in a controlled diagnostic setup only if the hardware permits a safe test. Two peripherals driving MISO can corrupt data or cause electrical contention; normal firmware must prevent that state.

Raise the clock only after a slow known-register read survives repeated transfers and resets. Capture select, clock and both data lines together when diagnosing a shifted value. An unchanged register is a better first timing check than a moving acceleration signal, because its expected bytes are known.

The module’s interface lesson is that a simple serial mechanism moves responsibility into the driver and board design. Explicit framing, mode ownership and readback checks let multiple peripherals share wires without pretending they share one universal command language. Component documentation and measured setup and hold margins determine the final rate.

32.6 Summary

SPI is a controller-clocked serial bus for short, deterministic peripheral transfers. It uses SCLK, MOSI, MISO, and chip select to frame transactions without a standard address or acknowledgement layer. That simplicity is useful for displays, converters, memory, radios, and sensors, but it requires disciplined records: clock mode, chip-select ownership, transaction framing, speed, voltage, board layout, and readback checks.

32.7 Key Takeaway

SPI is fast because it is explicit. Record the timing mode, chip-select map, transaction format, electrical assumptions, and diagnostic readback before treating a peripheral as production-ready.

32.8 See Also

Wired Communication Fundamentals

Review clocking, duplex behavior, bus topology, and physical wiring constraints.

I2C Protocol

Compare SPI with the address-based two-wire bus used for many low-speed sensors.

UART and RS-232

Contrast SPI with point-to-point asynchronous serial links used for modules and debug ports.

Wired Access: Ethernet

Move from board-level serial links to networked wired access when distance and infrastructure matter.