How would you implement a circular buffer for embedded systems?
Answer
A circular buffer (ring buffer) is a fixed-size FIFO queue that wraps around, commonly used for streaming data between ISRs and main code. Implementation: Use array with head (write) and tail (read) indices. Indices wrap around using modulo or masking (power-of-2 size). Full/empty conditions need careful handling. Key functions: put() - write at head, advance head. get() - read at tail, advance tail. isEmpty() - head == tail. isFull() - (head + 1) % size == tail (wastes one slot) or use counter. Embedded considerations: Volatile indices if ISR accesses buffer. Atomic operations or critical sections for multi-producer/consumer. Power-of-2 size enables fast modulo with bitwise AND. Consider cache line alignment for DMA. Lock-free possible with single producer/single consumer using memory barriers.
Master These Concepts with IIT Certification
175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.