Writing an OS Kernel from Scratch | SPI Bus — High-Speed Serial Communication
Have you ever wondered: How does a NOR Flash chip exchange data with the CPU? It has no address lines, no complex master-slave protocol — just 4 wires, yet it can transfer data at tens of MHz. This is SPI (Serial Peripheral Interface).
Compared to I2C, SPI is faster, simpler, and more suitable for high-speed scenarios. This article covers protocol principles, four modes, Daisy Chain, and finally Linux spidev debugging commands.
I. SPI Four Modes: CPOL and CPHA Combinations
SPI has 4 communication modes, determined by two parameters:
- CPOL (Clock Polarity): Clock level when idle (0=low, 1=high)
- CPHA (Clock Phase): Data sampling timing (0=first edge, 1=second edge)
Mode 0 (CPOL=0, CPHA=0): Idle low clock, sample on first edge
────────────────────────────────────────────────────
SCLK ───┐ ┌──────┐ ┌──────┐ ┌──
┌────┘ └────┘ └────┘
SDA ──[D7]──[D6]──[D5]──[D4]──[D3]──[D2]──...
MOSI ↑ ↑ ↑ ↑
Sample on first edge (CPHA=0)
Mode 3 (CPOL=1, CPHA=1): Idle high clock, sample on second edge
────────────────────────────────────────────────────
SCLK ───┘ ┌──────┐ ┌──────┐ ┌─
┌────┘ └────┘ └────┘
SDA ──[D7]──[D6]──[D5]──[D4]──[D3]──[D2]──...
↑ ↑ ↑
Sample on second edge (CPHA=1)Four modes quick reference:
| Mode | CPOL | CPHA | SCLK Idle | Sample Edge |
|---|---|---|---|---|
| 0 | 0 | 0 | Low | Rising |
| 1 | 0 | 1 | Low | Falling |
| 2 | 1 | 0 | High | Falling |
| 3 | 1 | 1 | High | Rising |
Common chip mode assignments:
- NOR Flash (W25Q64): Mode 0 or Mode 3
- SD card: Mode 0
- Sensors (gyroscope MPU6000): Mode 3
II. SPI Full-Duplex and Daisy Chain
SPI is a full-duplex bus, simultaneously having MOSI (Master Out Slave In) and MISO (Master In Slave Out). The master sends one byte while simultaneously receiving one byte.
Master Slave 1 Slave 2
│ │ │
MOSI ────────────────[D7..D0]─────────────────────────[D7..D0]──→ │
MISO ←───────────────[D7..D0]─────────────────────────[D7..D0]── │ │
│ │ │
SCLK ─────────────────────────[Clock]─────────────────────────
CS0 ───[L]──────────────────[H]──────────────────[H]
CS1 ───[H]──────────────────[H]──────────────────[H]
Daisy Chain (fewer CS lines):
Master → Slave1 (MISO) → Slave2 (MISO) → Master (MISO)
Data passes through daisy-chained devices
Requires more bits (all devices' data combined)III. SPI NOR Flash: Typical Application
SPI NOR Flash command set (W25Q64):
Read: 0x03 + 3-byte addr → data bytes
Fast Read: 0x0B + 3-byte addr + dmy → data bytes
Page Program: 0x02 + 3-byte addr + data (256 bytes max)
Sector Erase: 0x20 + 3-byte addr (4KB)
Chip Erase: 0xC7
Read JEDEC ID:
Send: 0x9F
Receive: MFR (1 byte) + Memory Type (1 byte) + Capacity (1 byte)
Example: 0xEF 0x40 0x17 → Winbond W25Q64
Linux commands:
$ flashrom -p linux_spi:dev=/dev/spidev0.0 -r backup.bin
$ hexdump /sys/bus/spi/devices/spi0.0/modalias
Comments