HeapCrash / Challenges / UART receive ring buffer

UART receive ring buffer

An AI assistant generated this interrupt-driven UART receiver for an STM32 at 115200 baud. It passed a quick bench test. Review it before it ships.

The code

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

#define RX_BUF_SIZE 64

static uint8_t rx_buf[RX_BUF_SIZE];
static uint8_t head = 0;
static uint8_t tail = 0;
static bool data_ready = false;

void USART2_IRQHandler(void)
{
    if (USART2->ISR & USART_ISR_RXNE) {
        uint8_t byte = USART2->RDR;
        rx_buf[head] = byte;
        head = (head + 1) % RX_BUF_SIZE;
        data_ready = true;
        printf("RX: %c\n", byte);
    }
}

/* Called from the main loop */
int uart_read(uint8_t *out)
{
    while (!data_ready) { }
    *out = rx_buf[tail];
    tail = (tail + 1) % RX_BUF_SIZE;
    if (tail == head) {
        data_ready = false;
    }
    return 1;
}

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