Simvik

Fix: the sensor ignores its configuration

A register write releases chip select while the last byte is still being clocked out. A medium embedded C problem (SPI), run and graded in the browser.

medium · SPI · find-the-bug · driver · spi · chip-select · busy

Bug report. imu_write(reg, value) writes one register of the motion sensor on SPI1 (chip select on PA4). Reads work, but writes never take effect: the sensor stays powered down after CTRL1 is written. Both peripherals are simulated like an STM32F4's; PA4's changes are reported, and so is each register the sensor stores. Fix it by changing one line (adding a line counts as one).

Starter code

static void spi_send(uint8_t b) {
  while (!(SPI1->SR & SPI_SR_TXE)) {
  }
  SPI1->DR = b;
}

void imu_write(uint8_t reg, uint8_t value) {
  cs_select();
  spi_send(reg & 0x7F);
  spi_send(value);
  cs_deselect();
  (void)SPI1->DR;   // drop what was clocked in, and clear the overrun it caused
  (void)SPI1->SR;
}

Example tests

Power the sensor up

spi_init();
imu_write(IMU_CTRL1, 0x60);
printf("CTRL1 = 0x%02X\n", imu_read(IMU_CTRL1));

Expected output:

gpioa: pin 4 high
gpioa: pin 4 low
imu: write 0x10 = 0x60
gpioa: pin 4 high
gpioa: pin 4 low
gpioa: pin 4 high
CTRL1 = 0x60

Learn it first

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

More SPI problems