Feed a daisy chain
Send bytes to a chain of 74HC595s so each chip shows its own pattern. An easy embedded C problem (SPI), run and graded in the browser.
easy · SPI · spi · shift-register
Several 74HC595 shift registers can share one SPI bus as a daisy chain: the microcontroller's MOSI feeds the first chip, its overflow output feeds the second, and so on. You send one byte per chip, then pulse the latch once, and the bytes end up spread along the chain.
Every byte sent pushes the earlier ones further along, so the first byte sent ends up in the chip furthest from the microcontroller.
Write chain_frame(outputs, n, send): outputs[0] is the pattern wanted on the chip nearest the microcontroller, outputs[n - 1] on the furthest. Fill send with the bytes in the order they must be transferred.
Starter code
void chain_frame(const uint8_t *outputs, int n, uint8_t *send) {
for (int i = 0; i < n; i++) send[i] = outputs[i];
}Example tests
Two chips
uint8_t want[2] = { 0x0F, 0xA0 }, send[2];
chain_frame(want, 2, send);
transfer_and_latch(send, 2);Expected output:
chip 0: 0x0F, chip 1: 0xA0Three chips
uint8_t want[3] = { 0x01, 0x02, 0x03 }, send[3];
chain_frame(want, 3, send);
transfer_and_latch(send, 3);Expected output:
chip 0: 0x01, chip 1: 0x02, chip 2: 0x03Learn it first
- SPI · Clock modes, chip select, multiple devices and throughput.
More SPI problems
- What an SPI mode means · Turn an SPI mode number into the clock's idle level and the edge that samples data.
- Split a flash write at page boundaries · Cut a write into Page Program commands that never cross a page.
- Read registers in a burst · Read several registers with one command, setting the read bit and skipping the command's reply.
- Driver: bring up SPI and read a sensor's ID · Configure an SPI master and its chip-select pin, then read one register from a sensor.
- Driver: read an accelerometer in one burst · Power a sensor up over SPI and read its three axes in one chip-select assertion.
- Fix: the sensor ignores its configuration · A register write releases chip select while the last byte is still being clocked out.
- Smartwatch: pixels for the display · Pack a 24-bit colour into the display's 16-bit RGB565 format, in the order SPI sends it.