Home / Learn Chip Programming / Circular (Ring) Buffers
Circular (Ring) Buffers
The standard queue for UART, ADC and logging: fixed size, no malloc, safe between ISR and main.
Theory in plain words
What it is
A ring buffer has head (write) and tail (read) indexes that wrap around. Empty when head == tail; full when next(head) == tail.
Why we use it
Serial data arrives from an interrupt faster than main can process. A ring buffer decouples them without dynamic memory.
How it works
ISR writes at head and advances it; main reads at tail and advances it. Only one side modifies each index, so it is lock free for one producer and one consumer.
Where it is used
- UART receive and transmit
- ADC streaming
- Event queues, log buffers
Ring buffer simulator
Push until FULL to see overrun. In real code, size the buffer for the worst burst and count overruns for debugging.
#define N 64 // power of two: use & (N-1) instead of %
static volatile uint8_t buf[N];
static volatile uint8_t head, tail;
void rb_put_isr(uint8_t b) { uint8_t nx = (head + 1) & (N - 1); if (nx != tail) { buf[head] = b; head = nx; } else overrun++; }
int rb_get(uint8_t *b) { if (head == tail) return 0; *b = buf[tail]; tail = (tail + 1) & (N - 1); return 1; }Quick quiz
1. When is the buffer empty?
No unread data between tail and head.
2. Why use a power of two size?
x & (N-1) is faster than %.
Common questions
When is the buffer empty?
head == tail. No unread data between tail and head.
Why use a power of two size?
Wrap with a cheap AND instead of modulo. x & (N-1) is faster than %.