ENع
→Superloop limits
الدرس 37 · Bare metal versus an RTOS

When the superloop is not enough

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة10 خطوات5 أسئلةAdvanced
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 37 · تفاعلي
01 / 10

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
}
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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
    }
  2. 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 ms
  3. One 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 ms
  4. A 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 entirely
  5. An 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: no
  6. Fix 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 machine
  7. Fix 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 here
  8. Waiting 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 else
  9. The 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 stopped
  10. The 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

اختبار يتاح بعد الخطوة الأخيرة.