Simvik

Driver: read an accelerometer in one burst

Power a sensor up over SPI and read its three axes in one chip-select assertion. A hard embedded C problem (SPI), run and graded in the browser.

hard · SPI · driver · spi · burst · endianness · sensor

The bus driver under Provided works. Write the sensor driver on top of it:

  • imu_write(reg, value) writes one register: chip select low, the address (bit 7 clear), the value, chip select high. The simulator reports each register the sensor stores, as imu: write 0x10 = 0x60.
  • imu_start() checks that WHO_AM_I reads 0x6B, returning -1 if not, then powers the sensor up by writing 0x60 to CTRL1 and returns 0.
  • imu_read_accel(out) reads the six output registers from OUTX_L in one burst: a single chip-select assertion, one address byte with the read bit, then six bytes, so all three axes come from the same sample. Store x, y and z in out[0..2] as signed 16-bit values.

Starter code

void imu_write(uint8_t reg, uint8_t value) {
}

int imu_start(void) {
  return -1;
}

void imu_read_accel(int16_t out[3]) {
}

Example tests

Start the sensor and read one sample

spi_init();
printf("start %d\n", imu_start());
int16_t a[3];
imu_read_accel(a);
printf("x %d y %d z %d\n", a[0], a[1], a[2]);

Expected output:

gpioa: pin 4 high
gpioa: pin 4 low
gpioa: pin 4 high
gpioa: pin 4 low
imu: write 0x10 = 0x60
gpioa: pin 4 high
start 0
gpioa: pin 4 low
gpioa: pin 4 high
x 1000 y -200 z 16384

Learn it first

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

More SPI problems