ISR-to-task patterns
Deferring work out of interrupts with semaphores, queues and notifications.
Keep the ISR short, do the work in a task
An interrupt handler runs at a priority above every task, blocks lower-priority interrupts, and cannot block or wait. So the rule in an RTOS is: the ISR does the minimum that must happen immediately (read the hardware, clear the flag, capture data), then hands the rest to a task. This is called deferred interrupt processing, and the task is sometimes called the "bottom half".
Benefits: the processing runs at a priority you choose, can use any RTOS API, can block, and does not add latency to other interrupts.
The four standard hand-offs
1. Binary semaphore: "something happened"
static SemaphoreHandle_t rx_sem;
void EXTI0_IRQHandler(void) {
BaseType_t woken = pdFALSE;
EXTI->PR = EXTI_PR_PR0; /* clear the source */
xSemaphoreGiveFromISR(rx_sem, &woken);
portYIELD_FROM_ISR(woken); /* switch now if the task outranks the current one */
}
void sensor_task(void *arg) {
for (;;) {
xSemaphoreTake(rx_sem, portMAX_DELAY); /* sleeps until the ISR gives */
read_fifo_and_process();
}
}
A binary semaphore only remembers one event: if the ISR gives twice before the task runs, the second is lost. Fine when the task drains everything each time (read the whole FIFO).
2. Counting semaphore: count events
When every event must be handled once, a counting semaphore remembers how many times it was given, up to its maximum.
3. Queue: pass the data
The ISR copies the data (a received byte, a timestamp, a small struct) into a queue; the task receives it. The data and the signal travel together, and nothing is shared.
void USART2_IRQHandler(void) {
BaseType_t woken = pdFALSE;
if (USART2->SR & USART_SR_RXNE) {
uint8_t b = (uint8_t)USART2->DR; /* reading DR clears RXNE */
if (xQueueSendFromISR(rx_queue, &b, &woken) != pdPASS) rx_overflows++;
}
portYIELD_FROM_ISR(woken);
}
A queue per byte is simple but costs a kernel call per byte. For high rates use a stream buffer or a ring buffer plus a notification.
4. Task notification: the lightweight option
FreeRTOS gives each task a built-in notification value. An ISR can signal a task directly, as a binary or counting semaphore, or by setting bits, with less RAM and faster than a separate object.
vTaskNotifyGiveFromISR(sensor_task_handle, &woken); /* in the ISR */
ulTaskNotifyTake(pdTRUE, portMAX_DELAY); /* in the task: returns the count */
Limitation: only one task can be the receiver.
The FromISR rules
- Use only
...FromISRAPI variants in interrupts; they never block. - Pass the
wokenflag and callportYIELD_FROM_ISRat the end. If the woken task has higher priority than the interrupted one, the context switch happens as the ISR exits; otherwise the woken task waits until the next switch. - The ISR's NVIC priority must be numerically at or above
configMAX_SYSCALL_INTERRUPT_PRIORITY(that is, logically lower or equal in urgency). Interrupts above that level must not call the kernel at all, but are never delayed by it.
Double buffering
For blocks of data (ADC samples, audio, a received frame), the ISR or DMA fills one buffer while the task processes the other, then they swap. The hand-off passes the index or pointer of the full buffer:
#include <stdio.h>
#include <stdint.h>
#define BLOCK 4
static int16_t buffers[2][BLOCK];
static volatile int filling = 0; /* which buffer the ISR writes */
static volatile int fill_pos = 0;
static volatile int ready = -1; /* buffer index handed to the task, -1 = none */
/* Called once per sample from the ADC interrupt (or DMA does this in hardware). */
static void adc_isr(int16_t sample) {
buffers[filling][fill_pos++] = sample;
if (fill_pos == BLOCK) {
ready = filling; /* hand the full buffer to the task (notify it) */
filling ^= 1; /* switch to the other buffer */
fill_pos = 0;
}
}
/* The processing task: runs when notified. */
static void process_task(void) {
if (ready < 0) return;
int32_t sum = 0;
for (int i = 0; i < BLOCK; i++) sum += buffers[ready][i];
printf("task: buffer %d average %d\n", ready, (int)(sum / BLOCK));
ready = -1;
}
int main(void) {
for (int n = 0; n < 12; n++) {
adc_isr((int16_t)(100 + n));
process_task(); /* in a real system: blocks on the notification */
}
return 0;
}
The task must finish with a buffer before the ISR needs it again; if it cannot keep up, use more buffers or a queue of buffer pointers, and detect the overrun.
Choosing
| Need | Use |
|---|---|
| Signal one task, data read by the task from hardware | Task notification (or binary semaphore) |
| Signal, every occurrence must be counted | Counting semaphore or notification as a counter |
| Pass small items | Queue |
| Pass a byte stream | Stream buffer or ring buffer + notification |
| Pass blocks | Double buffering or a queue of pointers to pool blocks |
| Several tasks must react to one event | Event group |
Pitfall: Doing "just a little" processing in the ISR grows over time: a CRC here, a log message there. Measure ISR execution time with a GPIO toggle or the cycle counter, and set a budget.
Interview question: Why call portYIELD_FROM_ISR at the end of an interrupt handler?
Answer: The FromISR call sets a flag if it unblocked a task with higher priority than the task that was interrupted. Calling portYIELD_FROM_ISR with that flag requests a context switch (by pending PendSV) as the ISR exits, so the woken task runs immediately instead of waiting for the next tick or the next voluntary switch. That minimises the latency from the interrupt to the deferred processing.
Interview question: Describe a design for handling a UART that receives bursts at 1 Mbit/s in an RTOS.
Answer: Use DMA in circular mode into a ring buffer so the hardware stores every byte, with the idle-line and half/full transfer interrupts. Each ISR only computes the new DMA write position and notifies a protocol task (task notification or stream buffer), then yields. The task, at a priority suited to the protocol's deadlines, reads the new bytes, frames and validates messages, and passes complete messages to consumers through queues. Count overruns and buffer-full events, and size the ring for the longest time the task may be delayed.
Build it: detect a blocked insulin line
This is step 4 of the module project. The dosing motor has an encoder that pulses as the plunger moves. If the tube is blocked (an occlusion), the motor is driven but the pulses stop, and the patient gets no insulin. The interrupt handler must stay tiny; the analysis belongs in a task.
Lab: Defer the work from the encoder interrupt to a task
encoder_isr(now)runs on every encoder pulse, with the current time in milliseconds. It does the minimum: it stores the timestamp in a queue of 16 and returns. When the queue is full it drops the pulse and counts it. No loops, no maths, no printing.motor_task(now, motor_on)runs every 10 ms. It takes all queued timestamps, adds them to the dose's pulse count and remembers the time of the latest pulse. While the motor is on, if the last pulse is more than 30 ms old, the line is blocked: it returnsALARM_OCCLUSION(once the alarm is raised, it stays raised untildose_start()). Otherwise it returnsALARM_NONE.dose_start(now)begins a dose: the pulse count goes to 0, the alarm is cleared, and the time counts as a pulse, so the motor gets 30 ms to start moving.dose_pulses()andpulses_dropped()return the counters.
Going deeper
Interview question: How would a barcode scanner handle characters arriving faster than it can decode them?
Answer: The UART interrupt (or DMA) only stores bytes in a ring buffer and signals a task, never parsing in the interrupt. The task decodes complete codes at its own pace. Size the buffer for the longest burst, count overruns, and keep the interrupt short so it never delays others.
Interview question: Why are task notifications faster than semaphores in FreeRTOS?
Answer: A notification is a value stored directly in the receiving task's control block, so giving it updates that task and possibly readies it without going through a separate kernel object and its wait list. That saves RAM (no object to create) and execution time, roughly 45 percent faster in FreeRTOS's own measurements for unblocking a task. The limit is that only that one task can receive it.
Interview question: What is a stream buffer and when is it better than a queue?
Answer: A stream buffer passes a stream of bytes of arbitrary length from one writer to one reader, such as an interrupt to a task, copying the bytes into a ring buffer without per-item overhead. It suits UART data and audio, where a queue of single bytes would cost a kernel call per byte. Message buffers add length-prefixed discrete messages on top. Both assume a single writer and single reader.
Explain it: In your own words, explain why an interrupt handler should defer its work to a task rather than doing it all itself.
Answer: An interrupt handler runs above every task, blocks interrupts of equal or lower priority while it runs and cannot block or call most kernel functions. Doing long work in it, such as parsing a message or writing flash, delays other interrupts and makes the whole system's timing unpredictable. Instead the handler does only what is urgent, such as reading the data and clearing the flag, then signals a task. The task does the processing at a priority chosen for its deadline, can block and use any service, and does not add latency to other interrupts.