Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Communication Buses

The SPI Bus

Learn how SPI works: master and slave shift registers, the four signals, clock polarity and phase modes, chip select, and a register read/write driver in embedded C.

When you need speed, SPI (Serial Peripheral Interface) is the usual choice. Flash memory chips, SD cards, displays, ADCs, radio modules and many sensors talk SPI at clock rates from a few hundred kilohertz to tens of megahertz. It is simple, fast and full duplex, and it has one big difference from UART: it is synchronous. The master generates a clock, so there is no baud rate to agree on and no start or stop bits.

In this lesson you will learn the four signals, how a transfer shifts data in both directions at once, what SPI "modes" mean, how multiple devices share the bus, and how a driver talks to a typical register-based sensor.

The four signals

Signal Also called Direction Purpose
SCK SCLK, CLK master to slave Clock generated by the master
MOSI SDO (master), SDI (slave), COPI master to slave Data from master
MISO SDI (master), SDO (slave), CIPO slave to master Data from slave
CS SS, NSS master to slave Chip select, normally active low

(Many datasheets now write COPI and CIPO, "controller out, peripheral in" and the reverse, instead of the older master/slave names. The wiring is the same.)

The master and the slave each contain a shift register. On every clock pulse, one bit leaves the master's register on MOSI while one bit leaves the slave's register on MISO, so after eight clocks the two bytes have been swapped. Every SPI transfer is therefore both a write and a read: to read from a slave, the master must send something (often 0x00 or 0xFF), and to write, it receives something it can ignore.

Selecting a slave

Each slave has its own chip-select line. The master pulls the CS of the target device low, performs one or more byte transfers, and releases CS. A slave whose CS is high ignores the clock and keeps its MISO output in high impedance, so several devices can share SCK, MOSI and MISO. The cost is one extra GPIO per device. (An alternative is a daisy chain, where the slaves' shift registers are linked in series, as with chains of shift registers or LED drivers.)

Chip select also frames a transaction. Many devices treat the falling edge as "a new command starts" and the rising edge as "command finished", so you must keep CS low across the whole command and its data bytes.

Modes: clock polarity and phase

The master and slave must agree on when data changes and when it is sampled. Two settings define that:

  • CPOL (clock polarity): the level of SCK when idle. CPOL = 0 means idle low, CPOL = 1 means idle high.
  • CPHA (clock phase): whether data is sampled on the first clock edge (CPHA = 0) or on the second (CPHA = 1).

The combinations form modes 0 to 3:

Mode CPOL CPHA Idle clock Data sampled on
0 0 0 low rising edge
1 0 1 low falling edge
2 1 0 high falling edge
3 1 1 high rising edge

Mode 0 is the most common. The datasheet of every SPI device states the mode it needs. Using the wrong one yields data shifted by a bit or all ones, and it is the first thing to check when a new SPI device returns garbage. Other settings are the bit order (almost always MSB first) and the clock speed, which must not exceed the slowest device on the bus.

A transfer, bit by bit

This program models mode 0 with MSB first. It keeps one shift register per side and prints the line levels for each clock pulse, so you can see the two bytes crossing.

C Two shift registers exchanging a byte

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

After eight clocks the master holds 0xA5 and the slave holds 0x3C. That is the entire hardware mechanism. Everything else, such as commands and register maps, is a convention built by the device on top of it.

Register-style devices

Most SPI sensors follow a simple convention. The first byte after CS falls is a command: a register address, with the top bit saying read (1) or write (0). In a read, the following clocks return register contents, usually with the address auto-incrementing, so reading several consecutive registers needs only one command (a burst read). Here is a simulated sensor and the driver code you would run on the master:

C A register read/write driver for a simulated sensor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice three habits that apply to any real driver. Read the WHO_AM_I register first: it proves the wiring, the mode and the chip select all work. Combine the two bytes into a signed 16-bit value (int16_t) when the sensor reports signed data, otherwise negative readings turn into large positive numbers. And keep the order of bytes straight: some chips send the high byte first, others the low byte first.

On real hardware, you call the vendor's HAL or write the SPI data register directly. A read-only example for an STM32-style HAL:

C
// Read-only: HAL call, not runnable here
uint8_t tx[3] = { 0x80 | 0x14, 0, 0 };
uint8_t rx[3];
HAL_GPIO_WritePin(CS_GPIO_Port, CS_Pin, GPIO_PIN_RESET);
HAL_SPI_TransmitReceive(&hspi1, tx, rx, 3, 100);   // rx[1], rx[2] hold the data
HAL_GPIO_WritePin(CS_GPIO_Port, CS_Pin, GPIO_PIN_SET);

Strengths, limits and tips

  • Fast and simple. No addressing overhead, full duplex, clock speeds up to tens of MHz. Good for flash, displays and memory.
  • No acknowledge. If the slave is absent, MISO floats and you read 0x00 or 0xFF with no error. Always verify an ID register.
  • No standard. Command formats differ from device to device; read the datasheet.
  • Pin count. Each slave needs a chip-select pin, and fast signals are sensitive to long wires.
  • Share the bus carefully. Keep CS high on idle devices and never let two slaves drive MISO at once. If an interrupt service routine and main code both use the same SPI bus, protect it with a lock or give the bus a single owner.
  • DMA. For large transfers (display frames, flash pages), let DMA fill and empty the SPI data register so the CPU is free.

SPI and I2C often compete for the same job. Choose SPI when you need speed or a bulk transfer, and I2C when you want only two wires for many slow devices.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In SPI, why is every transfer also a read?

    Both devices shift one bit out and one bit in per clock pulse, so after eight clocks each holds the other's byte.
  2. 2. A sensor needs idle clock low and data sampled on the rising edge. Which SPI mode is that?

    CPOL 0 means idle low; CPHA 0 means sampling on the first edge, which is the rising edge. That is mode 0.
  3. 3. You read WHO_AM_I and always get 0xFF. What is the most likely cause?

    SPI has no acknowledge, so an undriven MISO line commonly reads as all ones. Check wiring, chip select and mode.
  4. 4. What is a burst read?

    After the command byte, the device returns successive registers while CS stays low.

Summary

  • SPI uses SCK, MOSI, MISO and one chip select per slave; the master drives the clock.
  • Master and slave shift registers swap bytes on every transfer, so reading and writing happen together.
  • Modes 0 to 3 set clock idle level and sampling edge; the slave's datasheet tells you which one to use.
  • Register devices use an address byte with a read/write bit and often auto-increment; always check WHO_AM_I first.

Next: The I2C Bus