EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 34
Circular Buffers
Safe queues for serial data.
A circular buffer is a fixed array with a write position and a read position that wrap around at the end. An interrupt writes incoming bytes while the main loop reads them.
Because only one side changes each index, the pattern is safe for a simple producer and consumer. Choose a power-of-two size so wrapping is a cheap AND.
Decide in advance what happens when the buffer is full: drop new data or overwrite old.
EXAMPLE
#define N 16
volatile uint8_t buf[N], head = 0, tail = 0;
void put(uint8_t b) { buf[head] = b; head = (head + 1) & (N - 1); }
int get(void) { if (head == tail) return -1;
uint8_t b = buf[tail]; tail = (tail + 1) & (N - 1); return b; }