When the superloop is not enough
About this lesson
A superloop runs its jobs one after another, so anything that happens must wait for the whole pass. On an ESP32 with a button, a DS18B20 temperature sensor and an OLED screen, one readTemp() that waits 750 ms makes a pass 773 ms long, and a button press can wait that long too. See why an interrupt alone does not fix it, what cutting jobs up by hand costs, and how FreeRTOS tasks with priorities, vTaskDelay and a semaphore given from an ISR make the press go first. The lessons “setup() and loop(): the superloop”, “Interrupts in firmware: attachInterrupt, edges and latency” and “Non-blocking code: replacing delay()” cover the bare-metal side; the Operating systems lessons on semaphores and real-time scheduling give the theory.
One job at a time
Our ESP32 runs a superloop: loop() calls three jobs in order, then starts again, forever. The CPU, the part that runs code, can only do one job at a time. Check the button, read the temperature, draw the screen, repeat.
superloop loop() runs its jobs in order, forever
line 2 checkButton()
line 3 readTemp()
line 4 drawScreen()
one core: while one job runs, the others wait
// ESP32 (Arduino core): button on pin 0, DS18B20, SSD1306 OLED
void readTemp() {
startConversion(); // Convert T on the 1-Wire bus
delay(750); // DS18B20: up to 750 ms at 12 bits
temp = readScratchpad();
}
void loop() {
checkButton();
readTemp(); // 750 ms
drawScreen(); // 23 ms
}Read the lesson step by step
One job at a time
Our ESP32 runs a superloop: loop() calls three jobs in order, then starts again, forever. The CPU, the part that runs code, can only do one job at a time. Check the button, read the temperature, draw the screen, repeat.
superloop loop() runs its jobs in order, forever line 2 checkButton() line 3 readTemp() line 4 drawScreen() one core: while one job runs, the others wait // ESP32 (Arduino core): button on pin 0, DS18B20, SSD1306 OLED void readTemp() { startConversion(); // Convert T on the 1-Wire bus delay(750); // DS18B20: up to 750 ms at 12 bits temp = readScratchpad(); } void loop() { checkButton(); readTemp(); // 750 ms drawScreen(); // 23 ms }readTemp() waits 750 ms
The DS18B20 sensor needs up to 750 ms to measure at full 12-bit resolution. Our readTemp() asks, then waits with delay(750). For those 750 ms the CPU does nothing useful, and no other job can run.
line 3 readTemp(); startConversion() ask the sensor to measure delay(750) DS18B20 12-bit: up to 750 ms readScratchpad() fetch the answer CPU busy waiting for 750 msOne pass takes 773 ms
drawScreen() sends 1,024 bytes to the screen over I2C, about 23 ms at 400 kHz. Checking the button takes almost no time. So one pass of loop() is 750 + 23 = 773 ms: each job runs only once every 773 ms.
screen 128 x 64 pixels / 8 = 1,024 bytes I2C 9 clocks per byte (8 bits + ACK), 2.5 us each at 400 kHz 1024 x 9 x 2.5 us = 23.04 ms checkButton 0 ms readTemp 750 ms drawScreen 23 ms one pass 773 msA press waits 773 ms
Press the button just after checkButton() has looked. Nothing notices until the loop comes round again: up to 773 ms later. People feel a delay above about 100 ms, so the device feels slow. A quick tap may even end unseen.
t = 0 ms checkButton() looks: not pressed t = 1 ms the user presses t = 773 ms checkButton() looks again: pressed wait up to 773 ms (feels instant below ~100 ms) a tap shorter than one pass can be missed entirelyAn interrupt only half helps
An interrupt catches the press the instant it happens, so no tap is missed. Its ISR (interrupt service routine) must be short and cannot wait, so it only sets a flag. The real reaction still runs in loop(), up to 773 ms later.
ISR runs at once on the button edge pressed = true; (a volatile flag) loop() if (pressed) { ...react... } wait still up to 773 ms for the reaction caught: yes answered fast: noFix 1: cut the job up
Rewrite readTemp() so it never waits: start a reading, return, and collect it on a later pass once 750 ms have passed. A pass drops to about 23 ms. But every job must be cut up by hand, and one blocking job spoils it.
non-blocking readTemp(): if (!busy) { startConversion(); t0 = millis(); busy = true; } else if (millis() - t0 >= 750) { temp = readScratchpad(); busy = false; } one pass about 23 ms (drawScreen is now the longest job) cost every job becomes a hand-made state machineFix 2: tasks with priorities
An RTOS, a real-time operating system such as FreeRTOS, lets each job be its own task: a little loop with its own stack. Each task gets a priority, higher number meaning more urgent: button 3, screen 2, temp 1.
RTOS FreeRTOS, built into the ESP32 Arduino core task its own for (;;) loop and its own stack button priority 3 react to a press screen priority 2 redraw, 23 ms temp priority 1 read, waits 750 ms rule the highest-priority task that can run, runs // ESP32 (Arduino core ships FreeRTOS): three tasks SemaphoreHandle_t pressed; volatile float temp; void ARDUINO_ISR_ATTR onPress() { // runs on the button edge BaseType_t woken = pdFALSE; xSemaphoreGiveFromISR(pressed, &woken); if (woken) portYIELD_FROM_ISR(); // switch task on exit } void buttonTask(void *) { for (;;) { xSemaphoreTake(pressed, portMAX_DELAY); // Blocked until a press toggleLight(); } } void tempTask(void *) { for (;;) { startConversion(); vTaskDelay(pdMS_TO_TICKS(750)); // Blocked, CPU free temp = readScratchpad(); } } void screenTask(void *) { for (;;) { drawScreen(temp); vTaskDelay(pdMS_TO_TICKS(200)); } } void setup() { pinMode(0, INPUT_PULLUP); pressed = xSemaphoreCreateBinary(); attachInterrupt(0, onPress, FALLING); xTaskCreate(buttonTask, "button", 2048, NULL, 3, NULL); xTaskCreate(screenTask, "screen", 2048, NULL, 2, NULL); xTaskCreate(tempTask, "temp", 2048, NULL, 1, NULL); } void loop() { vTaskDelay(portMAX_DELAY); } // nothing left to do hereWaiting without the CPU
While the sensor measures, the temp task calls vTaskDelay(pdMS_TO_TICKS(750)): sleep 750 ms, counted in ticks, the RTOS's clock beats. It is Blocked, using no CPU time. The scheduler, the part of FreeRTOS that picks who runs, gives the CPU to the screen task.
tempTask vTaskDelay(pdMS_TO_TICKS(750)); state: Blocked (no CPU time) until the delay ends scheduler picks the highest-priority Ready task Ready: screen (2) -> screen runs the 750 ms wait no longer stops anyone elseThe press goes first
A press fires the ISR, which gives a semaphore with xSemaphoreGiveFromISR. That wakes the button task, priority 3, above the running screen task. FreeRTOS switches as the ISR ends: the press is handled at once, then the screen carries on.
ISR xSemaphoreGiveFromISR(pressed, &woken); woken = pdTRUE: a higher-priority task is now Ready portYIELD_FROM_ISR(); switch on the way out scheduler Ready: button (3), screen (2) -> button runs wait at once, not up to 773 ms then the screen task resumes where it stoppedThe price, and when to pay
Each task needs its own stack. Ours get 2,048 bytes, so three take 6 KB: fine in the ESP32's 520 KB, too much for an Uno's 2 KB. Shared data also needs care. Keep the superloop while one pass beats your tightest deadline.
stacks 3 x 2,048 bytes = 6 KB (+ a control block each) ESP32 520 KB SRAM: plenty Uno 2 KB SRAM: one stack would fill it all shared temp is written by one task, read by another -> locks and mutexes, later in this module rule one pass < tightest deadline -> superloop is fine
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A superloop calls checkButton() (almost 0 ms), readTemp() (750 ms) and drawScreen() (23 ms). At worst, how long can a button press wait to be noticed?
A press that lands just after checkButton() has looked waits for the rest of the pass: 750 + 23 = 773 ms. In a superloop the worst-case reaction time is the sum of the other jobs.
02You add an interrupt on the button pin that sets a flag. What does that fix?
The ISR runs at once, so the press is caught. But an ISR must be short and cannot wait, so it only sets a flag; loop() reacts to the flag the next time it gets round to it.
03The temp task calls vTaskDelay(pdMS_TO_TICKS(750)). What happens to the CPU during those 750 ms?
A Blocked task uses no processing time. The FreeRTOS scheduler always runs the highest-priority task that can run, so the screen task gets the CPU while the temp task waits.
04The screen task (priority 2) is running when the button ISR calls xSemaphoreGiveFromISR and wakes the button task (priority 3). What happens?
Giving the semaphore makes a higher-priority task Ready, so the ISR asks for a context switch on its way out. With preemptive scheduling the button task runs at once and the screen task resumes afterwards.
05Each of three tasks gets a 2,048-byte stack. Why is that a problem on an Arduino Uno but not on an ESP32?
Every task has its own stack in RAM: 3 × 2,048 bytes = 6 KB, three times the Uno's whole SRAM, but a small part of the ESP32's 520 KB.
Glossary
- Superloop
- Firmware built as one endless loop that calls each job in turn; Arduino's loop() is one.
- Worst-case reaction time
- The longest an event can wait before the code that handles it runs; in a superloop, up to one whole pass.
- RTOS
- A real-time operating system, such as FreeRTOS: a small kernel that runs many tasks and decides, by priority, which one has the CPU.
- Task
- One job written as its own endless loop with its own stack; the RTOS switches the CPU between tasks.
- Priority
- A number given to each task; in FreeRTOS a higher number means more urgent, and the highest-priority task that can run, runs.
- Blocked
- The state of a task that is waiting, for a delay or a semaphore; it uses no CPU time until the wait ends.
- Preemption
- Stopping the running task as soon as a higher-priority task becomes ready, and resuming it later.
- Semaphore (binary)
- A signal one side gives and another takes; a task that takes an empty one blocks until an ISR or another task gives it.
Notes and sources
- The card shows loop(); the panel shows the whole sketch. startConversion() and readScratchpad() stand for the usual OneWire calls (Convert T, then Read Scratchpad). checkButton() takes microseconds, so we count it as 0 ms; 773 ms is the sum of the other two jobs.
- 23 ms is a lower bound: 1,024 bytes x 9 clocks x 2.5 µs, the SSD1306's fastest I2C clock (400 kHz). The address and control bytes, and a slower 100 kHz bus, make a real redraw take longer.
- 750 ms is the DS18B20's maximum conversion time at 12 bits, its factory default. At 9 bits it is an eighth of that (93.75 ms), but readings are coarser.
- The ESP32 has two cores, and ESP-IDF's FreeRTOS can run two tasks at the same moment. To keep the picture simple we follow one core; the rule "the highest-priority Ready task runs" holds on each.
- temp is shared between two tasks. A float written by one task and read by another can need a mutex; the FreeRTOS mutex lesson later in this module shows how. The Operating systems lessons on semaphores and locks give the theory.
- Analog Devices (Maxim) DS18B20 datasheet: 750 ms conversion at 12 bits
- Solomon Systech SSD1306 datasheet: 128 x 64 display RAM and I2C timing
- J. Nielsen, Response Times: The 3 Important Limits (NN/g)
- Mastering the FreeRTOS Real Time Kernel, ch. 4: Task management
- FreeRTOS kernel source: task.h (vTaskDelay, pdMS_TO_TICKS, xTaskCreate)
- FreeRTOS kernel source: semphr.h (xSemaphoreGiveFromISR, xSemaphoreTake)
- ESP-IDF Programming Guide: FreeRTOS (IDF)
- Arduino-ESP32 documentation: GPIO and interrupts
- Arduino language reference: attachInterrupt()
- Espressif ESP32 Series datasheet
- Arduino UNO R3 product datasheet (A000066)
Quiz Unlocks after the last step.