Read registers in a burst
Read several registers with one command, setting the read bit and skipping the command's reply. A medium embedded C problem (SPI), run and graded in the…
medium · SPI · spi · drivers
SPI is full duplex: every byte sent clocks a byte back. Many sensors use this framing:
- select the chip (
cs_low()), - send a command byte: bit 7 set means read, the low bits are the first register,
- the byte that comes back during the command is junk (often a status byte): ignore it,
- send one dummy byte (0x00) per register to read; each reply is the next register,
- deselect (
cs_high()).
Write read_regs(reg, buf, n) to read n registers starting at reg into buf.
Starter code
void read_regs(uint8_t reg, uint8_t *buf, int n) {
cs_low();
buf[0] = spi_xfer(reg);
for (int i = 1; i < n; i++) buf[i] = spi_xfer(0x00);
cs_high();
}Example tests
The ID register
show(0x0F, 1);Expected output:
from 0x0F: 33Four data registers
show(0x10, 4);Expected output:
from 0x10: 12 34 56 78Learn 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.
- Feed a daisy chain · Send bytes to a chain of 74HC595s so each chip shows its own pattern.
- 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.