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 = 0x60Learn 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.
- Driver: read an accelerometer in one burst · Power a sensor up over SPI and read its three axes in one chip-select assertion.
- Smartwatch: pixels for the display · Pack a 24-bit colour into the display's 16-bit RGB565 format, in the order SPI sends it.