Write a UART receive interrupt handler with a ring buffer.
#include <stdint.h>
#include <stdbool.h>
#define UART_SR_RXNE (1u << 5)
#define UART_SR_ORE (1u << 3) /* overrun error */
#define RXQ 128u /* power of two */
static volatile uint8_t rxq[RXQ];
static volatile uint16_t rx_head; /* written only by the ISR */
static volatile uint16_t rx_tail; /* written only by the reader */
static volatile uint32_t rx_dropped, rx_overruns;
void UART_RX_IRQHandler(uart_t *u) /* called from the vector with the instance */
{
uint32_t sr = u->SR;
if (sr & (UART_SR_RXNE | UART_SR_ORE)) {
uint8_t b = (uint8_t)u->DR; /* reading DR clears RXNE (and ORE after SR read) */
if (sr & UART_SR_ORE) rx_overruns++;
uint16_t next = (uint16_t)((rx_head + 1u) & (RXQ - 1u));
if (next != rx_tail) { rxq[rx_head] = b; rx_head = next; }
else rx_dropped++; /* buffer full */
}
}
bool uart_getc(uint8_t *c) /* called from the main loop or a task */
{
if (rx_tail == rx_head) return false;
*c = rxq[rx_tail];
rx_tail = (uint16_t)((rx_tail + 1u) & (RXQ - 1u));
return true;
}
Points: read DR in every path that clears the interrupt; check and count errors (overrun, framing, noise) instead of ignoring them; single producer (ISR) and single consumer means each index has one writer, so no lock is needed on a single core; count dropped bytes so you can size the buffer. On a Cortex-M7 or multi-core system, add barriers (see the lock-free SPSC question).