SPI CPOL/CPHA Modes (0–3): Master/Slave Alignment Guide
← Back to: I²C / SPI / UART — Serial Peripheral Buses
This page explains how to correctly align SPI Mode 0–3 (CPOL/CPHA) between master and slave, so sampling happens inside the valid data window and bit-slip is avoided.
It provides a practical mapping model, frame-start (CS/first-bit) rules, and proof-by-test patterns so the chosen mode can be verified and kept stable across resets and firmware revisions.
Definition: What CPOL/CPHA Really Means (and What It Does Not)
CPOL/CPHA defines only two things: the idle level of SCLK and the sampling edge relative to the first clock transition after the bus leaves idle. Getting this definition wrong is the fastest way to create “looks-alive but misreads” behavior (bit-shift / bit-slip) across mixed-vendor masters and slaves.
Terminology (use one coordinate system)
- CPOL: SCLK idle level (the level when the bus is not clocking).
- Leading edge: the first SCLK transition after leaving idle (idle→active).
- Trailing edge: the second transition (active→idle direction within the cycle).
- CPHA: which edge is used for sampling (leading or trailing).
The #1 vendor-language trap
“First edge / second edge” is ambiguous unless it is anchored to idle. Some datasheets describe edges as rising/falling (absolute), while others describe leading/trailing (relative to CPOL).
- Always determine idle level first → then define leading/trailing.
- Do not treat “data valid on edge” as “sample on edge” (valid is a window, sample is a point).
What CPOL/CPHA does not define
- Bit order (MSB/LSB first), frame length, CRC policies.
- Chip-select polarity/behavior (CS timing is handled separately).
- Numeric setup/hold margins (addressed later as timing budget).
This page stays focused on edge alignment to prevent bit-shift/bit-slip.
Use this coordinate system everywhere: determine idle first (CPOL), then name leading/trailing edges, then place the sample point (CPHA).
Mode Map: Modes 0–3 in One Mental Model (No Tables Needed)
The fastest reliable mapping is: CPOL decides idle → CPHA decides sampling edge. Then the “other edge” becomes the natural shift/update edge (where the transmitter changes data), which is exactly why mismatched CPHA creates bit-shift and unstable reads.
30-second alignment workflow
- Find SCLK idle in the slave timing diagram → choose CPOL.
- Find the sampling edge (where data is captured) → choose CPHA as leading or trailing.
- Set MCU to the resulting Mode 0–3, then validate with a strong pattern (e.g., 0xAA/0x55, not all-zeros/all-ones).
A common mismatch pattern: the transmitter changes DATA on the same edge the receiver samples. The cure is always the same: anchor edges to idle, then set CPHA so sampling lands inside the stable window.
Quick anti-confusion rules (mixed-vendor safe)
- Always choose CPOL first: rising/falling only becomes meaningful after idle level is known.
- Sampling is a point: “data valid” describes a window; confirm where the receiver captures.
- Shift/update is the other edge: if the receiver samples on the update edge, bit-shift is expected.
Sampling vs Shifting: Where Bit-Slip Is Born
Bit-slip and bit-shift are rarely “mystery protocol bugs.” They usually happen when the receiver samples too close to the moment the transmitter updates DATA. If sampling lands in the change region, metastability and edge ambiguity turn into intermittent misreads—even when the link seems alive.
Failure signatures (what the errors look like)
- Fixed 1-bit shift: consistent bit offset across reads (classic edge mismatch).
- “Looks OK” with 0x00/0xFF, fails with 0xAA/0x55 (weak patterns hide timing risk).
- Only the first byte/bit is wrong: frame start is marginal (edge choice + start timing).
- Random, intermittent flips: sampling point sits near the boundary with low margin.
Root-cause shortlist (CPOL/CPHA only)
- CPHA mismatch: master updates DATA on the same edge the slave samples.
- Wrong edge naming: “first/second edge” interpreted without anchoring to idle.
- Sampling too close to update: stable window exists, but the sample point is placed near its edge.
- Decoder illusion: analysis tools decode with the wrong mode, masking the real mapping.
This section stays on edge alignment; signal-integrity fixes live in sibling pages.
Fast isolation checklist (minimal changes)
- Use a strong pattern (0xAA/0x55 or incrementing counter) to reveal bit-shift.
- Reduce SCLK by one step: if errors shrink, sampling margin is tight.
- Toggle CPHA only (keep CPOL fixed): disappearance or “signature change” confirms edge conflict.
When CPHA is wrong, sampling can coincide with the update edge. The goal is to move sampling into the stable window, away from the change region.
Master/Slave Alignment: Datasheet Language Traps (Cross-Vendor)
SPI timing is often described in incompatible phrases. The safe approach is to translate everything into one coordinate system: determine SCLK idle → name leading/trailing edges → locate the capture (sample) edge → derive CPOL/CPHA → pick Mode 0–3.
Translation dictionary (phrase → meaning)
If only a waveform is given (no mode stated)
- Read SCLK idle when not clocking → CPOL.
- Name leading edge as the first transition after idle.
- Locate capture (“sample/latched”) edge → CPHA.
- Sanity check: sampling should land inside the stable DATA window, not at the transition.
Treat datasheet timing as input data, not truth in prose form. Translate it into the same idle/edge coordinate system, then derive CPOL/CPHA deterministically.
CS, First Bit, and the “Phantom Shift” Problem (Within CPOL/CPHA Boundary)
Some “mode-like” failures are not caused by CPOL/CPHA at all. A common pattern is first-bit loss or first-bit misread at the frame start, which can look like a one-bit shift. This section stays strictly on timing relationships between CS, the first clock, and the first sampling point.
Frame start checklist (safe sequence)
- Assert CS (stable active level) and keep it quiet.
- Wait tCSS(min): CS→first SCLK edge spacing must meet the slave requirement.
- Present first bit on MOSI/MISO according to CPHA rules (see note below).
- Start clocking and keep CS stable for the full frame length.
- Deassert CS only after the last sample point is safely completed.
CPHA=1: sampling occurs later (trailing edge), but the first half-cycle must still be defined cleanly.
Phantom shift signatures (frame-start illusions)
- Only the first bit/byte is wrong, remaining bits look correct.
- Pattern-dependent failure: 0x00/0xFF looks fine, 0xAA/0x55 fails at the first byte.
- Intermittent one-bit offset after occasional CS glitches or early release.
- “Mode swap makes it worse”: changing CPOL/CPHA does not consistently fix the first-bit issue.
Boundary (avoid sibling-page overlap)
This section discusses CS/SCLK/DATA timing relationships only. It does not cover routing length, termination, ringing, or driver strength. Those belong to signal-integrity and long-trace design pages.
The first sample point must land inside a stable first-bit window. If CS timing is too tight or CS glitches, a “phantom shift” can appear even when CPOL/CPHA is correct.
Timing Budget: Setup/Hold Windows That Actually Matter for Mode Selection
Mode selection becomes robust when it is treated as window placement: CPHA decides where the sample point sits relative to the DATA update edge. The usable window is shaped by device timing (tSU/tHD), clock-to-data delays, and total uncertainty. This section focuses on the window model, not on signal-integrity details.
Budget template (structure, no hard numbers)
- half-period: time between edges used as update→sample spacing basis.
- tCO: clock-to-data delay at the transmitter side (launch path).
- tPD: logic/bridge/isolator delay along the data path (lumped).
- uncertainty: total edge/sample ambiguity (lumped guard band).
Pass criteria (quantitative, system-defined)
- X must be > 0: reserve headroom for non-ideal conditions.
- Use the same X across tests to avoid “it passed once” traps.
CPHA effect (window placement)
- CPHA=0: sample on leading edge → first-bit setup is stricter; sampling is closer to frame start.
- CPHA=1: sample on trailing edge → sampling is shifted later within the cycle; can increase usable window for some paths.
- In both cases, the sample point must land inside the stable window, away from the update edge.
Use the window model to choose CPHA: place the sample point away from the update edge and inside the stable window, then verify margin against the system-defined threshold.
Power-up Defaults & Safe Negotiation (Avoiding Silent Mismatches)
A mode mismatch at power-up can appear as “all-zeros,” “all-ones,” or occasional correct reads. Many controllers default to Mode 0, while the peripheral may expect a different CPOL/CPHA. A safe bring-up flow treats the default as untrusted and uses repeatable checks to lock the correct mode.
Bring-up playbook (power-up → lock)
- Start conservative: use a safe SCLK and stable CS timing.
- Try a candidate mode (CPOL/CPHA) with controlled parameters.
- Read a fixed ID/WHOAMI register multiple times (consistency matters).
- Run a strong pattern check (0xAA/0x55 or counter-based) to reveal bit-shift.
- Pass → lock configuration (mode + frequency + CS settings) for normal operation.
- Fail → advance to the next candidate mode (bounded attempts; no infinite loops).
- Persist the decided configuration if the system requires it (firmware config first; NVM only if applicable).
Logging fields (make bring-up reproducible)
- Mode: CPOL/CPHA (Mode 0/1/2/3).
- SCLK: frequency and divider/source.
- CS timing: tCSS / hold settings or configuration profile name.
- Probe: ID/WHOAMI read result and repetition count.
- Pattern: AA55 / counter / other.
- Failure signature: all-0, all-1, bit-shift, intermittent, timeout.
- Attempt index: which mode trial number.
- Context (optional): board revision, temperature, supply state.
A successful lock requires evidence (repeatable ID reads + strong patterns). Failures should be logged with signatures and bounded retries.
Verification: How to Prove the Mode Is Correct (Logic Analyzer + Golden Patterns)
Verification should be evidence-based: inspect raw edges and sampling points first, then use protocol decode as a cross-check. Weak patterns (0x00/0xFF) can hide bit shifts; strong patterns and repeatability are required to prove correctness.
Tool setup (raw first, decode second)
- Identify CS/SCLK/DATA channels and confirm voltage thresholds.
- Confirm SCLK idle level and edge placement (leading/trailing).
- Locate sampling relative to data stable windows (ignore decode at this step).
- Enable decode with the candidate mode and confirm it matches the raw observation.
Golden patterns (avoid weak tests)
- Too weak: 0x00 / 0xFF (can look “correct” even with shifts).
- Strong: 0xAA / 0x55 (reveals 1-bit shift quickly).
- Strong: incrementing counter (reveals dropped/repeated bits and frame-start issues).
- Optional: CRC or checksum (use as an extra indicator, not a substitute for edge checks).
Pass criteria (evidence-based)
- N should be > 1 (repeatability), not a single “lucky” pass.
- Patterns must include AA55 or counter to detect subtle shifts.
- Raw-edge confirmation must agree with decode configuration.
Strong patterns (AA55/counter) combined with repeatable trials are the fastest way to prove CPOL/CPHA correctness and rule out silent mismatches.
Debug Playbook: Bit-slip / Bit-shift Symptoms → Quickest Checks
Bit-slip and bit-shift failures should be treated as a structured workflow: classify the symptom, run the shortest checks in order, and apply actions that stay within CPOL/CPHA and frame-start boundaries. The goal is to avoid “lucky passes” and converge to evidence-based fixes.
- Confirm CPOL/CPHA mapping using leading/trailing edges.
- Verify the sample point is not on the data transition.
- Validate with 0xAA/0x55 (not 0x00/0xFF).
- Switch CPHA (0↔1) only after raw-edge confirmation.
- Re-verify frame start (CS + first bit) after any change.
- Run N repeated trials and record failure signatures (placeholder).
- Lower SCLK one step to test window margin sensitivity.
- Use AA55 or counter to avoid weak-pattern masking.
- Adopt the mode that places sampling deeper inside the stable window.
- Define a pass threshold: error rate < X (placeholder) at target SCLK.
- Reduce SCLK and confirm whether failures disappear (window shrinks at speed).
- Check the budget template: half-period vs (delays + uncertainty).
- Re-check CPHA placement (sample on leading vs trailing).
- Lock a conservative SCLK or choose a mode that increases sampling margin.
- Define margin ≥ X ns (placeholder) for the target rate.
- Do not use 0x00/0xFF for mode proof (too weak).
- Switch to AA55 and an incrementing counter.
- Repeat reads of a fixed ID register for consistency.
- Require strong patterns in verification gates (AA55/counter).
- Log the failure signature and stop treating “silent values” as success.
- Check CS → first SCLK spacing (tCSS) and stability.
- Confirm the first sample point lands in a stable first-bit window.
- Verify CPHA frame-start expectations (sample timing vs first bit).
- Increase tCSS (or insert a controlled wait) before the first clock edge.
- Lock CS behavior and re-verify with AA55 across N trials.
- Stop using decode as evidence; return to raw edge observation.
- Re-check frame start (CS + first bit) and strong patterns.
- Verify that the tested mode was actually applied per device.
- Re-run the controlled negotiation flow (mode scan + evidence).
- Lock the correct mode and verify repeatability (N trials).
Use the shortest path: confirm mode (raw edges) → confirm CS/first bit → down-shift SCLK to test window sensitivity → verify with strong patterns.
Design Hooks: Firmware & Register-map Practices to Prevent Mode Regressions
Many mode failures are regressions: a port, refactor, or board update silently restores defaults. Preventing this requires a clear configuration contract, a single source of truth for CPOL/CPHA per slave, a lightweight power-up self-test, and production hooks that enforce repeatability.
Regression-prevention checklist (contract first)
- Store CPOL/CPHA in a board config / device tree / init table (single source).
- Bind the contract per slave (do not assume one SPI bus = one mode).
- Apply config before traffic: load cfg → set mode → verify → enable.
- Record a config version/hash (placeholder) to detect unintended changes.
Lightweight power-up self-test (fast evidence)
- Read fixed ID/WHOAMI × N and require identical results (N placeholder).
- Run a short AA55 or counter test to expose subtle shifts.
- On failure, log signature and stop treating all-0/all-1 as success.
Production test hooks (ICT/ATE gates)
- Pass = N consistent trials + no bit shift + error rate < X (placeholders).
- Require at least one strong-pattern step (AA55/counter).
- Report the locked mode and config version/hash to the test log.
Treat CPOL/CPHA as a configuration contract per slave. Enforce it through init order, lightweight self-test, runtime counters, and production gates.
IC Selection Notes (Strictly CPOL/CPHA / Mode-Related)
Selection should reduce mode-risk, not create a “part recommendation” page. The checks below focus only on what directly impacts CPOL/CPHA alignment, frame start (CS + first bit), and proof of correctness.
Selection checklist (evidence-first)
- Timing diagram shows SCLK/MOSI/MISO/CS explicitly.
- Sampling edge is unambiguous (rising/falling or leading/trailing).
- Mode mapping is stated (Mode 0–3 or CPOL/CPHA spelled out).
- Supports multiple modes (ideal: M0–M3; otherwise document a fixed mode clearly).
- Mode behavior is stable across transactions (no hidden “mode changes” without explicit configuration).
- Explicit tCSS / tCSH / CS hold requirements are specified.
- First-bit stability relative to the first sample point is clear (ties directly to CPHA).
- Has a fixed ID/WHOAMI register for repeatable readback.
- Provides loopback/BIST or a strong integrity feature such as CRC (optional but valuable).
- Verification can use strong patterns (0xAA/0x55, counter) without relying on weak all-0/all-1 tests.
- Only “first/second edge” wording with no waveform to disambiguate.
- No CS timing guidance (frame start becomes guesswork).
- No strong verification hooks (hard to prove correctness and prevent regressions).
Example part numbers (for documentation/verification practice)
These are concrete examples commonly used in SPI contexts. Always verify the exact mode, timing, package, suffix, and availability from the latest datasheet.
- Winbond W25Q64JV
- Macronix MX25L12835F
- Micron MT25QL128ABA
- ST LSM6DSOX
- Bosch BMI270
- TDK InvenSense ICM-42688-P
- Analog Devices AD7685
- Texas Instruments ADS8320
- Microchip MCP3008
Prefer devices with explicit sampling-edge documentation, clear CS timing guidance, and verification hooks that enable strong-pattern proof.
Recommended topics you might also need
Request a Quote
FAQs (Mode 0–3 / CPOL/CPHA) — Troubleshooting Without Expanding Scope
Each FAQ uses the same 4-line structure so the result is executable and testable: Likely cause, Quick check, Fix, Pass criteria. Numeric thresholds use placeholders (X) that should be set by the system’s target rate and required error budget.