Skip to content
systemcoding.dev
RTOS

Send Queue Messages From an ISR With xQueueSendFromISR

Send data from an interrupt to a task with xQueueSendFromISR: the woken-task flag, portYIELD_FROM_ISR, interrupt priority rules and a full-queue policy.

6 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the C, Rust and GNU logos.

An interrupt handler has to be short, and the work that data triggers usually is not. The standard split is to capture the data in the interrupt, send it to a task through a queue and let the task do the processing. That needs a kernel call from interrupt context, and FreeRTOS provides a separate set of functions for it, because ordinary calls like xQueueSend may block and an interrupt must never block. This post covers xQueueSendFromISR: its signature, the pxHigherPriorityTaskWoken flag that most beginners misuse, the yield at the end of the handler, the interrupt priority rule that triggers the most common assertion and a policy for a full queue. It uses FreeRTOS Kernel V11.3.3 on a Cortex-M4F. The cornerstone guide on FreeRTOS queues, stream buffers and message buffers covers the family, and the post on vPortValidateInterruptPriority explains the priority failure in detail.

Why a separate function

xQueueSend can put the calling task to sleep when the queue is full, which only makes sense for a task. An interrupt is not a task. It has no context to put to sleep. The ISR version never blocks, and it takes an extra parameter that tells the handler whether a context switch is now needed.

xqueuesendfromisr_signature.cc
BaseType_t xQueueSendFromISR( QueueHandle_t xQueue,
                              const void * pvItemToQueue,
                              BaseType_t * pxHigherPriorityTaskWoken );

It returns pdTRUE if the item was queued and errQUEUE_FULL if there was no room, with no waiting. xQueueSendFromISR is a macro for xQueueSendToBackFromISR, and xQueueSendToFrontFromISR puts the item at the head.

The woken-task flag

If the item arrives while a task is blocked waiting to receive from the queue, the send makes that task ready. If the task's priority is higher than the task the interrupt interrupted, the right thing to do is to switch to it as soon as the interrupt finishes, not at the next tick. The kernel cannot do the switch inside your handler, so it reports the need through the flag.

You declare the flag in the handler, initialize it to pdFALSE and pass its address to every FromISR call. At the end of the handler, you pass it to portYIELD_FROM_ISR, which requests the context switch if the flag is pdTRUE:

uart_isr.cc
#include "FreeRTOS.h"
#include "queue.h"
#include "stm32f4xx.h"

extern QueueHandle_t xRxQueue;

void USART2_IRQHandler(void)
{
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;

    if (USART2->SR & USART_SR_RXNE)
    {
        uint8_t byte = (uint8_t) USART2->DR;           /* reading DR clears RXNE */

        if (xQueueSendFromISR(xRxQueue, &byte, &xHigherPriorityTaskWoken) != pdTRUE)
        {
            rx_overflow_count++;                       /* queue full: count, do not wait */
        }
    }

    portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}

The flag must be initialized to pdFALSE. The kernel sets it to pdTRUE if it unblocked a higher-priority task, and never clears it, which lets one handler make several FromISR calls with one flag and yield once at the end. An uninitialized flag is a classic bug: whatever junk is on the stack decides whether you yield.

On Cortex-M, portYIELD_FROM_ISR(x) sets the PendSV bit when x is true. The exception is taken on return from your handler, as described in the PendSV post, so the woken task starts running immediately instead of waiting for the tick.

The receiving task

The consumer is an ordinary task that blocks on the queue:

rx_task.cc
static void vRxTask(void *pvParameters)
{
    uint8_t byte;
    (void) pvParameters;

    for (;;)
    {
        if (xQueueReceive(xRxQueue, &byte, portMAX_DELAY) == pdPASS)
        {
            protocol_feed(byte);
        }
    }
}

void rx_init(void)
{
    xRxQueue = xQueueCreate(64, sizeof(uint8_t));
    configASSERT(xRxQueue != NULL);
    xTaskCreate(vRxTask, "rx", 256, NULL, 3, NULL);

    NVIC_SetPriority(USART2_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1);
    NVIC_EnableIRQ(USART2_IRQn);
    USART2->CR1 |= USART_CR1_RXNEIE;
}

A sequence of bytes arriving at 115,200 baud is one interrupt per byte, each queuing a byte, and the task drains the queue as fast as it can. The task blocked on an empty queue costs nothing between bytes.

The priority rule

The NVIC_SetPriority line in rx_init is not decoration. Every FromISR function has an assertion that the calling interrupt's priority is at or below the kernel's maximum syscall priority, meaning numerically equal to or greater than configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY. An interrupt left at the default priority of 0 trips the assertion the first time it calls the queue. The earlier post on that assertion covers diagnosis. In short: set the priority of every interrupt that calls the kernel, and never put it above the limit.

What to do when the queue is full

xQueueSendFromISR returns errQUEUE_FULL when the queue has no room, and the handler cannot wait. You have three policies.

Drop the new item and count it. This is the example above. It is the simplest, and it favors old data. Keep the counter, and report it, because a rising count tells you the queue or the consumer is undersized.

Overwrite the oldest. For a latest-value stream use a length-one queue with xQueueOverwriteFromISR, which never fails.

Defer the work. For a burst you cannot afford to lose, such as a DMA transfer completing, send one small item, a pointer or an index, and let the task do the rest. The post on passing large buffers through a queue of pointers shows the pattern.

overwrite_isr.cc
void ADC_IRQHandler(void)
{
    BaseType_t xWoken = pdFALSE;
    adc_reading_t r = { .value = (uint16_t) ADC1->DR };

    xQueueOverwriteFromISR(xLatestAdc, &r, &xWoken);
    portYIELD_FROM_ISR(xWoken);
}

Interrupt-safe habits

Several rules apply to any handler that calls the kernel.

**Use only FromISR functions.** xQueueSend, vTaskDelay and xSemaphoreTake in a handler corrupt the kernel or assert. In recent kernels vPortEnterCritical also asserts that it is not called from an interrupt, which catches some of these early.

Keep the handler short. Read the data, clear the flag, send, yield. A handler that formats a string or walks a table delays every lower-priority interrupt.

One flag, one yield. If the handler makes several FromISR calls, pass the same flag to each and call portYIELD_FROM_ISR once at the end.

Do not use the item after sending. The send copied it, so the handler's local variable is free to reuse, and the queue owns the copy.

Clear the interrupt source first or before returning. A level-triggered source that stays asserted re-enters the handler forever.

Testing it

You can check the pipeline without hardware by calling the handler logic from a test task, but real validation needs the interrupt. A reliable test sends a known sequence into the UART, such as bytes 0 to 255 repeated, and checks in the consumer that each byte follows the previous. A gap shows a drop, and a repeated value shows a bug in the read of the data register. Print the overflow counter at the end of the test:

Text
received 10000 bytes, in order, overflow count 0

A non-zero count at your target baud rate means the queue is too short for the consumer's worst-case latency, which the sizing post computes. At high rates, per-byte interrupts with a queue are the wrong tool altogether: a DMA transfer into a stream buffer moves the data with far fewer interrupts.

The boundary

xQueueSendFromISR is for single-core Cortex-M style interrupts that use the kernel's critical sections. On SMP builds, ISR-safe calls use spinlocks across cores, with extra rules in the port documentation. And the function is not a substitute for DMA: a byte per interrupt at a high data rate spends most of the CPU entering and leaving the handler.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.