DIY Electronics
— Building circuits, programming microcontrollers, and making things blinkWeekly DIY Electronics discussion thread
Implementing a Circular Buffer in C for Embedded
A circular buffer (ring buffer) is the correct data structure for streaming data in embedded systems — UART receive, ADC samples, log records.
Implementation: a byte array, a head index, a tail index, and the buffer size. Write to head (advance head after writing). Read from tail (advance tail after reading). Full condition: (head + 1) % size == tail. Empty condition: head == tail. The modulo operation is expensive on MCUs — use a power-of-2 size and replace % with & (bitwise AND with size-1).
Thread safety for a single producer and single consumer: if head is only written by the producer and tail is only written by the consumer, no mutex is needed on ARM Cortex-M (32-bit word writes and reads are atomic). However, on an 8-bit AVR, a 16-bit index variable update is not atomic — use a critical section (disable interrupts) around head/tail updates on 8-bit platforms.