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, asimu: write 0x10 = 0x60.imu_start()checks thatWHO_AM_Ireads0x6B, returning -1 if not, then powers the sensor up by writing0x60toCTRL1and returns 0.imu_read_accel(out)reads the six output registers fromOUTX_Lin 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 inout[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 16384Learn 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.
- 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.
- 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.