Interrupt-safe byte queue
A single-producer, single-consumer queue with 8-bit free-running indices that must survive wrapping. A hard embedded C problem (ISR-to-task patterns), run…
hard · ISR-to-task patterns · isr · lock-free · ring-buffer · wraparound
A UART receive interrupt pushes bytes and a task reads them in batches. There is no shared count field and no lock: the ISR is the only writer of head, the task the only writer of tail. Both are free-running: they only ever increase, wrapping from 255 to 0, and the slot index is the counter modulo Q_SIZE. The number of bytes waiting is always head - tail in 8-bit arithmetic.
q_isr_push(q, b): if the queue holdsQ_SIZEbytes, count the byte indropped; otherwise store it and advancehead.q_task_read(q, out, max): copy up tomaxwaiting bytes, oldest first, intoout, advancetailand return how many were copied.
The starter works until the counters wrap past 255. Make it correct forever.
Starter code
void q_isr_push(spsc_t *q, uint8_t b) {
if (q->head - q->tail >= Q_SIZE) {
q->dropped++;
return;
}
q->buf[q->head % Q_SIZE] = b;
q->head++;
}
uint8_t q_task_read(spsc_t *q, uint8_t *out, uint8_t max) {
uint8_t n = 0;
while (q->tail < q->head && n < max) {
out[n++] = q->buf[q->tail % Q_SIZE];
q->tail++;
}
return n;
}Example tests
Read a short message in batches of two
spsc_t q = {0};
push_str(&q, "hello");
read_all(&q, 2);Expected output:
read: [he] [ll] [o] dropped 0Keep going past 256 bytes
spsc_t q = {0};
uint8_t out[Q_SIZE];
for (int round = 0; round < 40; round++) {
push_str(&q, "abcdefg");
q_task_read(&q, out, Q_SIZE);
}
push_str(&q, "xyz");
read_all(&q, 8);Expected output:
read: [xyz] dropped 0Learn it first
- ISR-to-task patterns · Deferring work out of interrupts with semaphores, queues and notifications.
More ISR-to-task patterns problems
- Deferred interrupt lines · Record interrupts in a pending mask and let the task handle them in priority order.
- Fix: fast presses are lost · A button counter misses presses when they come faster than the main loop.