---
title: SPI, shift registers and displays
heading: A fast serial bus with a wire for every job
eyebrow: C12 · Lesson 32 · SPI, shift registers and displays
xp: 40
---

::: hook
Where I²C saves wires, **SPI** spends them for speed and simplicity: a clock, a wire out, a wire in, and a separate chip-select wire for each device. There are no addresses and no acknowledgments; the controller pulls a device's chip select low, clocks bytes out while bytes come back in at the same time, and lets chip select go. SPI runs at several megahertz, and it's how microcontrollers talk to flash memory, displays, SD cards and fast converters. Its simplest partner is a **shift register**, a chip that turns eight serial bits into eight output pins, here driving a seven-segment digit.
:::

::: play
- The program counts from 0 to 9 on a seven-segment digit, one number every 50 ms. Each update sends one byte over SPI (one bit per segment) into a shift register, which shows it when chip select (P13) rises.
- Zoom in on one update: CS falls, SCK pulses eight times while MOSI carries the byte, most significant bit first, then CS rises and the digit changes.
- The digit's patterns are in `SEGMENTS`. Change the entry for 8 to 0x80 and watch the 8 become a lone decimal point.
:::
:::

```sim board
lang: micropython
attach: display digit
scope: CS, SCK, MOSI | 0..0.2 ms
run: 0.55 s
code:
from machine import Pin, SPI
import time

# bits 0..6 light segments a..g; bit 7 is the decimal point
SEGMENTS = [0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F]

cs = Pin(13, Pin.OUT, value=1)
spi = SPI(0, baudrate=1000000)

def show(pattern):
    cs(0)                     # select the shift register
    spi.write(bytes([pattern]))
    cs(1)                     # rising edge: the outputs take the new byte

for n in range(10):
    show(SEGMENTS[n])
    time.sleep_ms(50)
```

::: predict
## Over SPI, a controller sends one byte to a device. How many bytes does it receive at the same time?

- [ ] None
- [x] One
- [ ] Two
- [ ] It depends on the device's address

::: reveal
One: SPI is **full duplex**. On every clock the controller shifts a bit out on MOSI and shifts a bit in from MISO, so sending n bytes always receives n bytes, though when only writing (as to a shift register) the bytes received are ignored. There are no addresses: chip select decides which device listens.
:::
:::

::: nameit
## The four wires

| Wire | Driven by | Job |
|---|---|---|
| SCK | controller | the clock |
| MOSI | controller | data to the device ("controller out") |
| MISO | device | data back ("controller in") |
| CS | controller | active low: selects one device |

Each device has its own CS. The controller sets CS low, clocks whole bytes (most significant bit first, usually), and sets CS high. In **mode 0** (this board's), data is read on SCK's rising edge and changes on its falling edge; the four modes differ in the clock's idle level and which edge samples.

## Speed

SCK runs at megahertz rates because nothing waits for an acknowledgment and the lines are actively driven both ways. This board's SPI clock is $f_\text{clk}/(2 \times \text{CLKDIV})$; a byte takes 8 clock periods.

## Shift registers

A 74HC595-style shift register takes a bit from its data input on each clock edge, shifting the rest along, and copies all eight into its output pins on its latch input's rising edge (here wired to CS). Its serial output can feed a second register: **daisy-chained**, n registers make an $8n$-bit output from three wires, sent as n bytes per update.

## Seven segments

Segments a to g (clockwise from the top, then the middle) and the point are bits 0 to 7, so a digit's pattern is a byte: 0 is a, b, c, d, e, f, which is 0x3F.
:::

::: example
## Which segments does 0x5B light, and what digit is it?

::: solution
1. **Write it in binary.**
   $$\text{0x5B} = 0101\,1011$$
   so bits 0, 1, 3, 4 and 6 are set.
2. **Map bits to segments.** Those are a, b, d, e and g: the top, upper right, bottom, lower left and middle.
3. **Read the digit.** That's a 2.

**Answer:** segments a, b, d, e and g, which make a 2.
:::
:::

::: example
## Four daisy-chained shift registers are updated over SPI at 2 MHz. How long does one update take?

::: solution
1. **Count the bits.** Four bytes is 32 bits.
2. **Time on the wire.** Each bit takes 0.5 µs at 2 MHz:
   $$32 \times 0.5\ \mu\text{s} = 16\ \mu\text{s}$$
   plus the CS edges.
3. **Compare with I²C.** The same 32 outputs over I²C at 400 kHz would take over 100 µs.

**Answer:** about 16 µs, plus the CS edges.
:::
:::

::: example
## A 24-bit ADC is read over SPI at 4 MHz. How long does a reading take on the wire?

::: solution
1. **Time on the wire.** 24 clocks at 250 ns:
   $$24 \times 250\ \text{ns} = 6\ \mu\text{s}$$
2. **Why SPI is fast.** SPI has no addressing or acknowledge bits, so its time is just the bits, which makes it the fast choice for converters and displays.

**Answer:** 6 µs.
:::
:::

::: check
given: CLKDIV = 1 | 2 | 5 | 10
answer: 10/(2*CLKDIV)
unit: MHz
tolerance: 0.5%

## This board's SPI clock is $f_\text{clk}/(2 \times \text{CLKDIV})$. What's the SPI clock with CLKDIV = {CLKDIV}?

::: right
Right. {answer} MHz.
:::

::: misses
- [10/CLKDIV] CLKDIV sets each half of the clock period.
- [any] Not yet. $10\text{ MHz}/(2 \times \text{CLKDIV})$.
:::
:::

::: check
given: n = 1 | 4 | 16; f = 1 | 4 | 8
answer: n*8/f
unit: µs
tolerance: 0.5%

## How long does it take to clock {n} bytes over SPI at {f} MHz?

::: right
Right. {answer} µs.
:::

::: misses
- [n*9/f] SPI has no acknowledgment bit: 8 clocks per byte.
- [any] Not yet. Bits over the clock rate.
:::
:::

::: check
given: d = 1 | 3 | 4 | 7
base: 16
answer: 6*(step(d - 0.5) - step(d - 1.5)) + 79*(step(d - 2.5) - step(d - 3.5)) + 102*(step(d - 3.5) - step(d - 4.5)) + 7*(step(d - 6.5) - step(d - 7.5))

## Segments a to g are bits 0 to 6. Light exactly the segments that show the digit {d}. What byte is that, in hex?

::: right
Right. {answer:hex2}.
:::

::: misses
- [any] Not yet. Set the bit for each segment the digit uses: a top, b upper right, c lower right, d bottom, e lower left, f upper left, g middle.
:::
:::

::: check
given: k = 1 | 2 | 4 | 6; o = 8
answer: k*o
tolerance: 0

## How many output pins do {k} daisy-chained 8-bit shift registers give?

::: right
Right. {answer}, from three wires.
:::

::: misses
- [any] Not yet. 8 outputs per register.
:::
:::

::: check
given: v = 0x3F | 0x5B | 0x80 | 0x6D; k = 1 | 4 | 8
answer: floor(v/2^(8 - k)) - 2*floor(v/2^(9 - k))
tolerance: 0

## SPI sends {v:hex2} most significant bit first. What level is the {k}th bit on MOSI?

::: right
Right. The {k}th bit sent is bit 8 − {k}: {answer}.
:::

::: misses
- [any] Not yet. Most significant first: the first bit is bit 7.
:::
:::

::: check
kind: choice

## Three SPI devices share SCK, MOSI and MISO. How does the controller choose which one it's talking to?

- [ ] By sending its address first
- [x] By pulling only that device's chip select low
- [ ] By using a different clock speed for each
- [ ] By waiting for the device's acknowledgment

::: misses
- [1] SPI has no addresses; that's I²C.
- [3] Every device sees the same clock.
- [4] SPI has no acknowledgments.
:::
:::

::: check
kind: c
given: D = 2 | 4 | 7 | 9
attach: display digit
run: 0.01
expect: latched = 91*(step(D - 1.5) - step(D - 2.5)) + 102*(step(D - 3.5) - step(D - 4.5)) + 7*(step(D - 6.5) - step(D - 7.5)) + 111*(step(D - 8.5) - step(D - 9.5))

## Show the digit `D` ({D}) on the seven-segment display: CS is P13 (active low, latching on its rise), and the byte goes over SPI.

```c starter
#include "board.h"

int main(void) {
    GPIO_DIR = 1 << 13;
    SPI_DATA = D;
    return 0;
}
```

```c solution
#include "board.h"

const uint8_t segments[10] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F};

int main(void) {
    GPIO_DIR = 1 << 13;
    GPIO_SET = 1 << 13;
    GPIO_CLR = 1 << 13;              // select
    SPI_DATA = segments[D];
    while (SPI_STATUS & SPI_BUSY) ;  // wait for all 8 bits
    GPIO_SET = 1 << 13;              // latch
    return 0;
}
```

::: right
Right: select, send, wait for the transfer to finish, then latch.
:::
:::

::: check
kind: micropython
given: n = 1 | 3 | 5 | 8
attach: display bar
run: 0.02
expect: latched = 2^n - 1

## Eight LEDs hang off the shift register (bit 0 is the bottom LED). Light the bottom {n} of them, as a level meter would.

```micropython starter
from machine import Pin, SPI

cs = Pin(13, Pin.OUT, value=1)
spi = SPI(0)
spi.write(bytes([n]))
```

```micropython solution
from machine import Pin, SPI

cs = Pin(13, Pin.OUT, value=1)
spi = SPI(0)
cs(0)
spi.write(bytes([(1 << n) - 1]))
cs(1)
```

::: right
Right. $2^n - 1$ has the low {n} bits set; chip select around the write latches it.
:::
:::

::: check
kind: parts
given: n = 8 | 16 | 24; f = 1 | 4 | 10

## An SPI transfer of {n} bits runs at {f} MHz.

::: part
answer: n/f
unit: µs
tolerance: 0.5%

### How long does it take?

::: misses
- [any] Bits ÷ clock rate.
:::
:::

::: part
answer: f*1e6/n
tolerance: 0.5%

### How many transfers a second could it make back to back?

::: misses
- [any] The reciprocal.
:::
:::
:::

::: check
kind: parts
given: k = 2 | 4 | 8; f = 1 | 2 | 8

## {k} daisy-chained 8-bit shift registers are updated over SPI at {f} MHz.

::: part
answer: 8*k/f
unit: µs
tolerance: 0.5%

### How long does one update take?

::: misses
- [any] 8 bits per register.
:::
:::

::: part
answer: 8*k
tolerance: 0

### How many clock pulses is that?

::: misses
- [any] One per bit.
:::
:::
:::

::: explain
## Why is SPI usually much faster than I²C?

::: model
I²C's lines are open-drain, pulled up by resistors, so every rising edge is a slow RC charge, which limits the clock to hundreds of kilohertz; and every byte carries a ninth clock for the acknowledgment, plus addresses and start and stop conditions. SPI's lines are driven actively both high and low, so edges are fast and the clock can run at many megahertz; there are no acknowledgments or addresses, since a dedicated chip-select wire picks the device; and it's full duplex, moving a byte each way every eight clocks. The price is wires: four, plus one more chip select per extra device.
:::
:::

::: practice

::: check
given: CLKDIV = 1 | 2 | 4 | 5 | 10 | 25 | 50
answer: 10/(2*CLKDIV)
unit: MHz
tolerance: 0.5%

## SPI clock with CLKDIV {CLKDIV}?

::: misses
- [any] $f_\text{clk}/(2 \times \text{CLKDIV})$.
:::
:::

::: check
given: n = 2 | 64; f = 2 | 10
answer: n*8/f
unit: µs
tolerance: 0.5%

## Time for {n} bytes at {f} MHz?

::: misses
- [any] 8 clocks per byte.
:::
:::

::: check
given: k = 2..8 int
answer: 8*k
tolerance: 0

## Outputs from {k} chained shift registers?

::: misses
- [any] 8 each.
:::
:::
:::
