HeapCrash / Challenges / Sharing SPI between tasks

Sharing SPI between tasks

A display task and an SD-card logger share one SPI bus. A medium-priority comms task (priority 2) also exists. The display stutters, and sometimes the logger never runs again.

RTOSMedium3 bugs~6 minRTOS and concurrency

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.

SemaphoreHandle_t spi_lock;

void app_init(void)
{
    spi_lock = xSemaphoreCreateBinary();
    xSemaphoreGive(spi_lock);
}

void display_task(void *p)    /* priority 3 */
{
    for (;;) {
        xSemaphoreTake(spi_lock, portMAX_DELAY);
        lcd_flush();
        xSemaphoreGive(spi_lock);
    }
}

void logger_task(void *p)     /* priority 1 */
{
    for (;;) {
        xSemaphoreTake(spi_lock, portMAX_DELAY);
        sd_write_block();
        if (sd_error()) continue;
        xSemaphoreGive(spi_lock);
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

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