FreeRTOS queues: xQueueSend from tasks and ISRs
About this lesson
A FreeRTOS queue is a small first-in, first-out box of fixed-size slots that the kernel owns. One job copies an item in, another copies it out, and a task waiting on an empty queue sleeps without using the CPU. On an ESP32 you follow a queue of 3 characters: a keys task (priority 2) sends what you type, a logger task (priority 1) prints it, a fourth key is lost when the queue is full, and a button's interrupt routine sends with xQueueSendFromISR and switches straight to the logger. The general producer-consumer problem lives in the OS course; how the kernel picks a task each tick is in “The FreeRTOS tick and how it picks a task”; sharing data with an ISR by hand is in “volatile and sharing data with an ISR”.
A box with three slots
Two jobs need to pass data safely. setup() calls xQueueCreate(3, sizeof(char)): the kernel sets aside a queue of 3 slots, each 1 byte. A queue is first in, first out (FIFO): items leave in the order they came.
queue a FIFO box of fixed slots, owned by the kernel
line 1 q = xQueueCreate(3, sizeof(char));
3 slots x 1 byte
sender copies an item in at the back
reader copies the oldest item out at the front
// ESP32 DevKitC, Arduino core. Serial Monitor at 115200, "No line ending".
// Type keys to send them; press the button on GPIO 4 (to GND) to send B.
QueueHandle_t q;
const int BUTTON = 4;
void keysTask(void *) { // priority 2
for (;;) {
while (Serial.available()) {
char c = Serial.read();
if (xQueueSend(q, &c, 0) != pdPASS) // wait 0 ticks for space
Serial.println("queue full, key lost");
}
vTaskDelay(pdMS_TO_TICKS(20)); // Blocked for 20 ms
}
}
void loggerTask(void *) { // priority 1
char c;
for (;;) {
xQueueReceive(q, &c, portMAX_DELAY); // Blocked until an item comes
Serial.printf("got %c\n", c);
}
}
void ARDUINO_ISR_ATTR onButton() {
char c = 'B';
BaseType_t woken = pdFALSE;
xQueueSendFromISR(q, &c, &woken); // never waits
portYIELD_FROM_ISR(woken); // switch now if a higher task woke
}
void setup() {
Serial.begin(115200);
q = xQueueCreate(3, sizeof(char));
pinMode(BUTTON, INPUT_PULLUP);
attachInterrupt(BUTTON, onButton, FALLING);
xTaskCreatePinnedToCore(keysTask, "keys", 4096, NULL, 2, NULL, 1);
xTaskCreatePinnedToCore(loggerTask, "logger", 4096, NULL, 1, NULL, 1);
}
void loop() { vTaskDelay(portMAX_DELAY); } // loop() has nothing to doRead the lesson step by step
A box with three slots
Two jobs need to pass data safely. setup() calls xQueueCreate(3, sizeof(char)): the kernel sets aside a queue of 3 slots, each 1 byte. A queue is first in, first out (FIFO): items leave in the order they came.
queue a FIFO box of fixed slots, owned by the kernel line 1 q = xQueueCreate(3, sizeof(char)); 3 slots x 1 byte sender copies an item in at the back reader copies the oldest item out at the front // ESP32 DevKitC, Arduino core. Serial Monitor at 115200, "No line ending". // Type keys to send them; press the button on GPIO 4 (to GND) to send B. QueueHandle_t q; const int BUTTON = 4; void keysTask(void *) { // priority 2 for (;;) { while (Serial.available()) { char c = Serial.read(); if (xQueueSend(q, &c, 0) != pdPASS) // wait 0 ticks for space Serial.println("queue full, key lost"); } vTaskDelay(pdMS_TO_TICKS(20)); // Blocked for 20 ms } } void loggerTask(void *) { // priority 1 char c; for (;;) { xQueueReceive(q, &c, portMAX_DELAY); // Blocked until an item comes Serial.printf("got %c\n", c); } } void ARDUINO_ISR_ATTR onButton() { char c = 'B'; BaseType_t woken = pdFALSE; xQueueSendFromISR(q, &c, &woken); // never waits portYIELD_FROM_ISR(woken); // switch now if a higher task woke } void setup() { Serial.begin(115200); q = xQueueCreate(3, sizeof(char)); pinMode(BUTTON, INPUT_PULLUP); attachInterrupt(BUTTON, onButton, FALLING); xTaskCreatePinnedToCore(keysTask, "keys", 4096, NULL, 2, NULL, 1); xTaskCreatePinnedToCore(loggerTask, "logger", 4096, NULL, 1, NULL, 1); } void loop() { vTaskDelay(portMAX_DELAY); } // loop() has nothing to doWaiting costs nothing
The logger calls xQueueReceive with portMAX_DELAY: wait for as long as it takes. The queue is empty, so the logger becomes Blocked and uses no CPU time. The keys task is also Blocked, in its 20 ms delay. Core 1 runs the idle task.
line 2 xQueueReceive(q, &c, portMAX_DELAY); queue empty -> logger: Blocked Blocked uses no processing time; the kernel wakes it keys Blocked in vTaskDelay(pdMS_TO_TICKS(20)) core 1 runs the idle task (priority 0)Send: '7' is copied in
You type 7890. When its 20 ms delay ends, the keys task wakes and calls xQueueSend. The kernel copies '7' into slot 0: a copy, not a pointer. The logger turns Ready, but keys has priority 2, higher than 1, so keys keeps the CPU.
typed 7 8 9 0 line 3 xQueueSend(q, &c, 0) c = '7' slot 0 '7' (copied byte for byte) logger Blocked -> Ready (an item is waiting) keys priority 2 > logger 1: keys keeps runningThe queue fills in order
The loop sends '8' into slot 1 and '9' into slot 2. Each new item joins at the back. Now all 3 slots are full, and the logger is still waiting its turn for the CPU.
send '8' -> slot 1 send '9' -> slot 2 queue '7' '8' '9' 3 of 3 full order first in, first outFull: '0' is lost
xQueueSend for '0' finds no free slot. Its last argument is how long to wait, in ticks; we passed 0, so it returns errQUEUE_FULL at once and the key is dropped. A longer wait, like pdMS_TO_TICKS(10), would block keys until a slot frees.
send '0' -> queue full wait 0 ticks -> returns errQUEUE_FULL now sketch prints "queue full, key lost" or wait pdMS_TO_TICKS(10): keys Blocked until a slot frees or 10 ms pass tick the kernel's timer interrupt; waits count in ticksOldest first, out it comes
Keys goes back to its 20 ms delay and blocks. Now the logger is the highest-priority task that can run. Each xQueueReceive copies out the oldest item and frees its slot: '7', then '8', then '9'. Empty again, the logger blocks.
keys vTaskDelay(20 ms) -> Blocked logger highest priority that can run -> Running receive slot 0 -> '7' prints "got 7" receive slot 1 -> '8' prints "got 8" receive slot 2 -> '9' prints "got 9" queue empty -> logger Blocked again, core 1 idleAn interrupt sends too
You press the button. Its ISR interrupts the idle task. An ISR is not a task, so it can never block: it must use xQueueSendFromISR, which never waits. 'B' lands in slot 0: the queue is a ring, so writing wraps around.
button GPIO 4 falls -> onButton() interrupts idle line 4 xQueueSendFromISR(q, &c, &woken); c = 'B' rule inside an ISR only call ...FromISR functions slot 0 'B' (the write position wrapped) logger Blocked -> ReadyReturn straight into the logger
The send woke the logger, priority 1, higher than the interrupted idle task, so woken became pdTRUE. portYIELD_FROM_ISR(woken) makes the interrupt return into the logger, which copies 'B' out of slot 0 and prints it. Without it, the logger could wait until the next tick.
woken logger 1 > idle 0 -> pdTRUE line 5 portYIELD_FROM_ISR(woken); return into the logger, not idle prints "got B" without logger stays Ready until the scheduler next runs: at worst the next tick interrupt
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A queue was made with xQueueCreate(3, sizeof(char)). The keys task sends '7', '8' and '9', then the logger receives once. What does it get?
Queues are first in, first out: the reader always gets the oldest item, and it gets a copy of the bytes, not a pointer.
02The logger calls xQueueReceive(q, &c, portMAX_DELAY) and the queue is empty. What happens?
A task that waits on a queue enters the Blocked state, which uses no processing time. With portMAX_DELAY (and INCLUDE_vTaskSuspend set to 1) it waits without a timeout; the kernel unblocks it when an item comes.
03The queue is full and the keys task calls xQueueSend(q, &c, 0). What happens?
The last argument is the longest time to wait for space, in ticks. With 0 the call returns at once; it returns errQUEUE_FULL because no slot was free.
04Why must a button's interrupt routine use xQueueSendFromISR instead of xQueueSend?
FreeRTOS says never to call an API function without FromISR in its name from an ISR. There is no calling task to block, so the FromISR versions never wait.
05The ISR's send wakes the logger (priority 1) while the idle task (priority 0) was running. What does portYIELD_FROM_ISR(woken) do?
xQueueSendFromISR set woken to pdTRUE because the unblocked task has a higher priority than the one that was interrupted. Without the yield the logger would stay Ready until the scheduler next runs, at worst the next tick interrupt.
Glossary
- Queue
- A first-in, first-out store of fixed-size items owned by the RTOS kernel. Senders copy items in at the back; receivers copy the oldest one out.
- Task
- One job in FreeRTOS: a function with its own stack and a priority. The scheduler runs the highest-priority task that is able to run.
- Blocked state
- A task waiting for something, like an item in a queue or a delay to end. It uses no CPU time until the kernel wakes it.
- Ready state
- A task that could run but is waiting for the CPU: a higher-priority task holds it, or a task of equal priority has its turn first.
- Tick
- A periodic timer interrupt the kernel uses to keep time. Wait times such as xTicksToWait are counted in ticks; pdMS_TO_TICKS converts milliseconds.
- ISR
- Interrupt service routine: a short function the hardware runs when an event like a button press happens. It is not a task and cannot wait.
- xQueueSendFromISR
- The interrupt-safe way to send to a queue. It never blocks and reports through a flag whether a higher-priority task was woken.
- portYIELD_FROM_ISR
- Asks the scheduler to switch tasks as the interrupt ends, so a task woken by the ISR runs at once.
Notes and sources
- The card shows the five queue calls only. The whole sketch, under the steps, wraps them in the keys task, the logger task, the button ISR and setup(). xQueueSend returns pdPASS when the item went in.
- The ESP32 has two cores and FreeRTOS runs an idle task on each. The sketch pins both tasks to core 1 so one core tells the story; the button interrupt and Wi-Fi details of the second core are left out.
- A real button bounces, so one press can fire the interrupt several times and send several B items. The lesson Debouncing a button shows how to filter that.
- The keys task sees "7890" in one go only if all four characters reach the serial buffer before it next looks; at 115200 baud they take well under its 20 ms delay. In ESP-IDF, task stack sizes such as 4096 are in bytes, not words.
- FreeRTOS-Kernel: queue.h (API reference comments for xQueueCreate, xQueueSend, xQueueReceive, xQueueSendFromISR)
- R. Barry, Mastering the FreeRTOS Real Time Kernel, ch. 4: Task Management
- R. Barry, Mastering the FreeRTOS Real Time Kernel, ch. 5: Queue Management
- R. Barry, Mastering the FreeRTOS Real Time Kernel, ch. 7: Interrupt Management
- Espressif ESP-IDF Programming Guide: FreeRTOS (IDF) on the ESP32
- Espressif Arduino-ESP32: GPIO API (attachInterrupt, INPUT_PULLUP)
- Espressif Arduino-ESP32 core: main.cpp (loopTask priority)
Quiz Unlocks after the last step.