ENع
←FreeRTOS queues
Lesson 40 · Bare metal versus an RTOS

FreeRTOS queues: xQueueSend from tasks and ISRs

14 min8 steps5 questionsAdvanced
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”.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 40 · Interactive
01 / 08

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 do
Loading figure…
or ← →
Read the lesson step by step
  1. 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 do
  2. Waiting 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)
  3. 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 running
  4. The 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 out
  5. Full: '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 ticks
  6. Oldest 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 idle
  7. An 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 -> Ready
  8. Return 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

Quiz Unlocks after the last step.