JAlcocerTech E-books

Chapter 8 — Firmware That Keeps Running: Loops, Sleep, Watchdogs and OTA

Getting a sensor to print a reading takes ten minutes (Chapter 4). Getting a node to keep sending correct readings for months, unattended, on a solar panel, is a different job. That job is firmware.

Bare Loop or RTOS?

There are two ways to structure the code on a microcontroller:

A bare loop (setup() + loop() in Arduino, a while True: in MicroPython). Easy to read, almost no memory overhead. It breaks down as soon as one task blocks: a slow WiFi reconnect stalls the sensor read, and a stuck sensor read stalls everything.

An RTOS (real-time operating system) runs several tasks with their own timing: one reads sensors, one handles the network, one blinks a status LED. It costs memory and a learning curve.

On the ESP32 you already have one: the Arduino core and MicroPython both run on top of FreeRTOS (via ESP-IDF). You can stay with a simple loop and add FreeRTOS tasks only when one job starts blocking another.

For a sensor node that reads, publishes and sleeps, a bare loop is the right choice. Reach for tasks when the node also has to react: valves, alarms, local displays (Chapter 6).

A Read Loop That Handles Failure

The minimal DHT22 loop on an ESP32 (Arduino), with the one check most examples skip:

#include "DHT.h"

#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  dht.begin();
}

void loop() {
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();

  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("DHT22 read failed");   // count it, don't publish it
  } else {
    Serial.printf("T=%.1f C  RH=%.1f %%\n", temperature, humidity);
  }

  delay(2000);  // the DHT22's minimum interval (Chapter 7)
}

A failed read returns NaN. Publish that to MQTT and your Grafana panels (Chapter 17) fill with gaps or garbage. Treat it as an event to count instead: a node whose failure count climbs has a wiring or condensation problem.

Sleep Is the Architecture

Chapters 5 and 6 made the case: on battery, deep sleep between readings is not optional. In firmware terms that changes the shape of the program. After deep sleep the ESP32 doesn’t resume where it left off. It reboots and runs from the top.

So a battery node’s firmware is not a loop at all. It’s a straight line:

# MicroPython on ESP32: one wake cycle
import machine, dht, time

sensor = dht.DHT22(machine.Pin(4))

def cycle():
    sensor.measure()
    reading = (sensor.temperature(), sensor.humidity())
    # connect WiFi, publish over MQTT (Chapter 4), disconnect
    return reading

try:
    cycle()
finally:
    machine.deepsleep(5 * 60 * 1000)   # sleep 5 minutes, then reboot into this file

Consequences:

  • Anything you need across wakes (last value sent, failure counts) has to live in RTC memory or flash, not in a variable.
  • WiFi connect time dominates the energy budget. The radio is the most expensive part of each cycle, so send less often and send more per message (Chapter 10 covers batching).
  • finally matters. If the cycle throws and never reaches the sleep call, the node stays awake and drains the battery.

Watchdogs: Reboot Instead of Hang

A watchdog timer reboots the board if your code stops “feeding” it within a set time. It’s the cheapest reliability feature you’ll ever add:

from machine import WDT
wdt = WDT(timeout=30000)   # 30 s

while True:
    read_and_publish()
    wdt.feed()             # if read_and_publish hangs, the board resets
    time.sleep(10)

A hung MQTT connect or a sensor that never answers then costs one reboot, not a silent node you only notice days later in the monitoring dashboard (Chapter 16).

Updating Without a Ladder

Once a node is on a balcony or in a greenhouse, re-flashing over USB means going to fetch it. Over-the-air (OTA) updates solve that:

node checks for a new version → downloads → verifies → reboots → runs it
  • Arduino / ESP-IDF: OTA is built in (the ArduinoOTA library, or a dual-partition update from a URL). If the new image fails to boot, the board can fall back to the previous one.
  • MicroPython: no single built-in mechanism. The usual approach is for the node to pull updated .py files over HTTP from a server you control, for example a container on the homelab (Chapter 1).

Build OTA in before the node leaves your desk. Adding it later means fetching the node anyway.

The Checklist

Before a node goes into the field:

  • Sensor reads have a timeout and failed reads are handled, not published
  • A watchdog resets the board if anything hangs
  • Battery nodes deep-sleep, and the sleep call is in a finally
  • State that must survive a wake lives in RTC memory or flash
  • Battery voltage is published along with the readings
  • OTA works, tested on the desk
  • The node publishes an “online” message, and MQTT’s Last Will reports it offline (Chapter 9)

Takeaway: A sensor node’s firmware is a short, failure-aware wake cycle, not a clever loop. Handle bad reads, sleep in a finally, add a watchdog, and ship OTA on day one.