A ring buffer in C for a UART interrupt, step by step
head written only by the producer, tail written only by the consumer), and acquire/release atomic indexes in both directions. Use it in an ISR only when those atomic operations are lock-free and supported in that context by the target toolchain.A UART receive interrupt fires, you read one byte, and your main loop needs to process it later. The structure that sits between them is almost always a ring buffer (also called a circular buffer or FIFO). It is also one of the most common firmware interview questions, and one of the easiest to get subtly wrong.
The design in one paragraph
Keep a fixed array, a head index where the producer writes next, and a tail index where the consumer reads next. The producer is the interrupt handler. The consumer is your main loop. Because each index is written by exactly one side, you do not need to disable interrupts around the buffer, provided the indexes are accessed with the correct ordering and the target supports ISR-safe, lock-free atomic loads and stores. The buffer is for exactly one producer and one consumer.
Why a power-of-two size
If the size is a power of two, you can wrap an index with i & (SIZE - 1) instead of a modulo or a compare-and-reset. On a core without a hardware divider that is a real saving, and it makes the code branch-free.
Free-running indexes remove the "full or empty?" ambiguity
The classic bug: with indexes that wrap at the array size, head == tail means both "empty" and "full". The fix used below is to let head and tail count freely (they wrap at 65536, which is a multiple of the buffer size) and mask only when indexing the array. Then:
- Empty means
head == tail. - Full means
(uint16_t)(head - tail) == SIZE. - Fill level is simply
(uint16_t)(head - tail), and unsigned subtraction handles wrap-around correctly.
The code
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdatomic.h>
#define RB_SIZE 16u /* power of two, smaller than the uint16_t counter range */
_Static_assert(RB_SIZE > 0u && RB_SIZE <= UINT16_MAX &&
(RB_SIZE & (RB_SIZE - 1u)) == 0u, "invalid ring size");
typedef struct {
uint8_t buf[RB_SIZE];
_Atomic uint16_t head; /* written only by the producer (ISR) */
_Atomic uint16_t tail; /* written only by the consumer (main) */
} rb_t;
static bool rb_push(rb_t *r, uint8_t b)
{
uint16_t h = atomic_load_explicit(&r->head, memory_order_relaxed);
uint16_t t = atomic_load_explicit(&r->tail, memory_order_acquire);
if ((uint16_t)(h - t) == RB_SIZE) {
return false; /* full: drop and let caller count it */
}
r->buf[h & (RB_SIZE - 1u)] = b;
atomic_store_explicit(&r->head, (uint16_t)(h + 1u), memory_order_release);
return true;
}
static bool rb_pop(rb_t *r, uint8_t *b)
{
uint16_t t = atomic_load_explicit(&r->tail, memory_order_relaxed);
uint16_t h = atomic_load_explicit(&r->head, memory_order_acquire);
if (t == h) {
return false; /* empty */
}
*b = r->buf[t & (RB_SIZE - 1u)];
atomic_store_explicit(&r->tail, (uint16_t)(t + 1u), memory_order_release);
return true;
}
int main(void)
{
rb_t r = {0};
atomic_init(&r.head, 0);
atomic_init(&r.tail, 0);
uint8_t v;
unsigned dropped = 0;
for (unsigned i = 0; i < 20; i++) { /* 20 pushes into 16 slots */
if (!rb_push(&r, (uint8_t)i)) { dropped++; }
}
printf("pushed 20, dropped %u, fill %u\n", dropped, (unsigned)(uint16_t)(r.head - r.tail));
for (unsigned i = 0; i < 16; i++) {
if (!rb_pop(&r, &v) || v != i) { puts("FAIL order"); return 1; }
}
printf("popped 16 in order, empty now: %s\n", rb_pop(&r, &v) ? "no" : "yes");
/* run many wrap-arounds of the 16-bit indexes */
unsigned long sum_in = 0, sum_out = 0;
for (unsigned long n = 0; n < 200000ul; n++) {
(void)rb_push(&r, (uint8_t)n); sum_in += (uint8_t)n;
if (!rb_pop(&r, &v)) { puts("FAIL pop"); return 1; }
sum_out += v;
}
printf("200000 push/pop pairs across index wrap: %s\n", sum_in == sum_out ? "ok" : "MISMATCH");
return sum_in == sum_out ? 0 : 1;
}
pushed 20, dropped 4, fill 16 popped 16 in order, empty now: yes 200000 push/pop pairs across index wrap: ok
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the memory ordering is for
There are two ownership transfers. The producer writes the byte before publishing head with release semantics; the consumer acquires head before reading that byte. The consumer reads the byte before publishing tail with release semantics; the producer acquires tail before reusing that slot. Both directions matter. Each side can read its own index with relaxed ordering because it is the sole writer of that index.
This C11 pattern is valid for ordinary shared memory between threads when the implementation supports the atomic types. For interrupt handlers, ISO C alone does not define MCU interrupt behavior: verify that the actual index objects are lock-free, suitably aligned, and that the compiler and MCU support these operations in an ISR. Inspect the generated code; a helper that takes a lock can deadlock if interrupted. If those conditions do not hold, use a documented target-specific critical section or RTOS ISR-safe queue. DMA and non-coherent shared memory require additional target-specific cache and ordering rules. The sequential host test below the implementation demonstrates FIFO and wraparound behavior, not concurrent timing or hardware correctness.
Common mistakes
- Both sides write the same index. If your pop also resets
headwhen empty, you have two writers, and you now need a critical section. - A non-power-of-two size with free-running indexes. The wrap at 65536 would then land in the middle of the array and silently corrupt the order.
- Forgetting overflow policy. Decide on purpose whether a full buffer drops the newest byte (as above) or overwrites the oldest, and count the drops so you can see overruns in the field. Overwriting the oldest requires a different ownership protocol; the producer must not simply modify the consumer's tail.
- **Making
bufthe only shared thing.** The indexes are shared too; ordinary non-atomic shared indexes do not provide synchronization.volatilealone is not a replacement for the acquire/release operations.
If you want to understand why volatile is needed but not sufficient on its own, read what volatile does in C.
Walk through a four-slot circular buffer
Imagine four slots numbered 0 to 3. Start with an empty queue. Writing A, B and C occupies slots 0, 1 and 2. Reading A and B leaves C in slot 2. Writing D and E uses slots 3 and 0. The next item read is C, not E: FIFO order follows the read position, not the visual order of array indexes.
| Operation | Read next | Write next | Occupied slots |
|---|---|---|---|
| Initialize | 0 | 0 | 0 |
| Add A, B, C | 0 | 3 | 3 |
| Read A, B | 2 | 3 | 1 |
| Add D, E | 2 | 1 | 3 |
The illustrated positions are masked indexes; the implementation above retains the complete free-running counters. Try the circular queue in the Firmware Visual Lab.
How many bytes should the queue hold?
For an illustrative 115200 baud link with 8N1 framing, each byte takes ten bit periods. A consumer that cannot run for 5 milliseconds may accumulate about 58 bytes, assuming continuous traffic. Add any existing backlog, scheduling jitter and a margin. A capacity of 64 is only adequate if the resulting worst-case backlog fits and the consumer subsequently catches up. Measure the actual high-water mark and drops. See ring buffer capacity and overflow for the distinction between reserved-slot and full-capacity designs.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.
Keep reading
- Ring buffer capacity: full and empty are not the same
- What
volatilereally does in C, and what it does not - Bit tricks every firmware engineer should know
- Data structures and algorithms for firmware: what to learn, in what order
- Learn embedded C programming
- RTOS fundamentals for firmware engineers
- All articles