HeapCrash / Challenges / SPI writes that don't stick

SPI writes that don't stick

SPI1 on an STM32L4 (FIFO-based SPI, 8-bit frames, FRXTH set) talks to a sensor at 8 MHz. The sensor auto-increments its register address during a burst. Register writes sometimes don't stick, the logic analyser shows an extra 0x00 after every byte written, and a read straight after a write returns stale data.

The code

Embedded C for Cortex-M. It compiles. There are 3 real bugs in it: the kind that pass a bench test and fail in the field.

uint8_t spi_xfer(uint8_t b)
{
    while (!(SPI1->SR & SPI_SR_TXE)) { }
    *(volatile uint8_t *)&SPI1->DR = b;
    while (!(SPI1->SR & SPI_SR_RXNE)) { }
    return *(volatile uint8_t *)&SPI1->DR;
}

void sensor_write(uint8_t reg, const uint8_t *d, int n)
{
    CS_LOW();
    SPI1->DR = reg;
    for (int i = 0; i < n; i++) {
        while (!(SPI1->SR & SPI_SR_TXE)) { }
        SPI1->DR = d[i];
    }
    while (!(SPI1->SR & SPI_SR_TXE)) { }
    CS_HIGH();
}

uint8_t sensor_read(uint8_t reg)
{
    CS_LOW();
    spi_xfer(reg | 0x80u);
    uint8_t v = spi_xfer(0);
    CS_HIGH();
    return v;
}

What an interviewer expects

The bugs, reference fixes and the follow-up question are in the practice app, after you've tried it.

Companies that test this

Matched on the skills each company's embedded roles emphasise.

Related challenges

Flag the lines, say what breaks, then fix it and build it with clang in your browser.

Find the bugs