Implement a ring buffer that overwrites the oldest data when full.
#include <stdint.h>
#include <stdbool.h>
#define LOG_SIZE 64u /* power of two */
typedef struct { int16_t buf[LOG_SIZE]; uint32_t head, count; } log_ring_t;
void log_push(log_ring_t *r, int16_t v)
{
r->buf[r->head] = v;
r->head = (r->head + 1u) & (LOG_SIZE - 1u);
if (r->count < LOG_SIZE) r->count++; /* once full, the oldest entry is overwritten */
}
/* i = 0 is the oldest entry still stored */
bool log_get(const log_ring_t *r, uint32_t i, int16_t *v)
{
if (i >= r->count) return false;
uint32_t oldest = (r->head - r->count) & (LOG_SIZE - 1u);
*v = r->buf[(oldest + i) & (LOG_SIZE - 1u)];
return true;
}
Points: used for "last N samples" (oscilloscope pre-trigger buffers, moving averages) and crash logs ("last N events before the fault", often kept in a .noinit RAM section). The oldest index is derived from head and count. If a separate reader consumes concurrently, overwriting means the writer also moves the reader's tail, which needs a lock or a sequence counter.