Simvik

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: 33

Four data registers

show(0x10, 4);

Expected output:

from 0x10: 12 34 56 78

Learn it first

  • SPI · Clock modes, chip select, multiple devices and throughput.

More SPI problems