Implement an ISR-safe queue (interrupt producer, task consumer) using a critical section.
#include <stdint.h>
#include <stdbool.h>
typedef struct { uint16_t id; uint8_t len; uint8_t data[8]; } msg_t; /* e.g. a CAN frame */
#define MQ 16u
static msg_t mq[MQ];
static volatile unsigned mq_head, mq_tail, mq_count;
uint32_t irq_save(void); /* save PRIMASK and disable interrupts */
void irq_restore(uint32_t s);
bool mq_put_from_isr(const msg_t *m) /* called only from the ISR */
{
if (mq_count == MQ) return false;
mq[mq_head] = *m;
mq_head = (mq_head + 1u) % MQ;
mq_count++;
return true;
}
bool mq_get(msg_t *out) /* called from task context */
{
bool ok = false;
uint32_t s = irq_save(); /* short critical section: copy one message */
if (mq_count) {
*out = mq[mq_tail];
mq_tail = (mq_tail + 1u) % MQ;
mq_count--;
ok = true;
}
irq_restore(s);
return ok;
}
Points: the shared count is modified by both sides, so the task side needs a critical section (the ISR cannot be interrupted by the task on a single core, so it needs none, unless a higher-priority ISR also uses the queue). Keep the critical section to a single copy. Alternatives: the lock-free SPSC ring (no shared counter), or an RTOS queue with xQueueSendFromISR and a context-switch request.