↓ Skip to main content
  1. Engineering Notes & Articles/

Building Reliable Systems: Low Power Techniques, Sleep Modes, and Watchdog Timers

Embedded Systems Fundamentals - This article is part of a series.
Part 7: This Article

Building a prototype that runs smoothly on your workbench—plugged into unlimited USB power with a Reset button right in front of you—is one thing. Deploying that device into the field to operate unattended in a farm, on a rooftop, or inside a factory machine room for months without human intervention is an entirely different challenge.

In the real world, two enemies kill deployed embedded projects faster than anything else: batteries draining far sooner than planned, and firmware suddenly freezing (hanging) due to electrical noise, dropped radio links, or a rare bug that only surfaces on day 30.

To defeat both, every embedded engineer relies on two pillars of system resilience: low-power management (Low Power & Sleep Modes) and automatic recovery mechanisms (Watchdog Timer and Brown-Out Detection).


1. Understanding the Power Budget: Why IoT Devices Drain Batteries
#

Many beginners are shocked when their DIY Wi-Fi sensor node powered by a 2000 mAh 18650 Li-Ion battery dies in less than a day. Yet the numbers make the reason obvious: a microcontroller running continuously awake (especially with its Wi-Fi radio active) draws an average of 80–150 mA.

The secret to making battery-powered devices last months or years is not buying a gigantic battery, but shrinking the active Duty Cycle—keeping the microcontroller “asleep” for 99% of its life, waking only briefly to read sensors and transmit data.

To estimate battery life realistically, we calculate the average current ($I_{\text{avg}}$):

$$I_{\text{avg}} = \frac{(I_{\text{active}} \times T_{\text{active}}) + (I_{\text{sleep}} \times T_{\text{sleep}})}{T_{\text{active}} + T_{\text{sleep}}}$$$$\text{Battery Life (hours)} \approx \frac{\text{Battery Capacity (mAh)} \times \eta}{I_{\text{avg}}\text{ (mA)}}$$

(Where $\eta$ is the effective battery efficiency factor—typically taken as around $0.8$ to account for cutoff voltage, temperature derating, and self-discharge.)

Real-World Simulation: Always-On vs. Deep Sleep
#

Suppose you have a 2000 mAh battery ($\eta = 0.8 \rightarrow$ effective capacity 1600 mAh) powering an IoT temperature sensor that reports every 10 minutes (600 seconds):

  • Scenario A — No Sleep Mode (Waiting with delay() or millis()): The device stays continuously awake at an average current of $I_{\text{active}} = 80\text{ mA}$.
$$\text{Battery Life} = \frac{1600\text{ mAh}}{80\text{ mA}} = \mathbf{20\text{ hours}}$$

(Not even a full day before the battery is completely dead!)

  • Scenario B — Using Deep Sleep: The device wakes for $T_{\text{active}} = 2\text{ seconds}$ ($80\text{ mA}$) to sample the sensor and transmit data, then immediately sleeps for $T_{\text{sleep}} = 598\text{ seconds}$ at a sleep current of $I_{\text{sleep}} = 20\text{ }\mu\text{A}$ ($0.02\text{ mA}$).
$$I_{\text{avg}} = \frac{(80 \times 2) + (0.02 \times 598)}{600} = \frac{171.96}{600} \approx \mathbf{0.287\text{ mA}}$$$$\text{Battery Life} = \frac{1600\text{ mAh}}{0.287\text{ mA}} \approx 5{,}582\text{ hours} \approx \mathbf{232\text{ days (7.7 months!)}}$$

Simply by changing the firmware strategy on the exact same battery, runtime jumps from 20 hours to nearly 8 months.

The “Race to Sleep” Principle: Many engineers assume lowering the CPU clock frequency always saves power. In practice, for short bursts of computation (like encryption or signal filtering), running the CPU faster to finish in 50 ms and immediately entering Deep Sleep often consumes less total energy (Joules) than running slowly for 500 ms while keeping other peripherals awake longer.


2. Dissecting Microcontroller Sleep Mode Tiers
#

Every silicon vendor (Espressif, STMicroelectronics, Nordic) uses slightly different names for its sleep states, but architecturally almost all modern microcontrollers share similar power-saving tiers—the deeper the sleep, the lower the current, but the more subsystems are powered down and the longer the wake-up time.

Power Mode Common Names (ESP32 / STM32) CPU & Clock State RAM State Wake-Up Time Typical Current Key Characteristics
Active Active / Run Fully active Retained — 10 – 240 mA CPU, peripherals, and radio operate normally.
Idle / Modem Sleep Modem Sleep / Sleep CPU paused or Radio off Retained Microseconds (µs) 1 – 20 mA Execution resumes instantly; leveraged by RTOS Tickless Idle when all tasks are Blocked.
Light Sleep Light Sleep / Stop Mode CPU & main clock off Retained Tens of µs – ms 0.05 – 1.5 mA Program resumes right at the next line of code upon wake-up without rebooting.
Deep Sleep Deep Sleep / Standby CPU, clocks, & peripherals off Lost (except small RTC RAM) Milliseconds – hundreds of ms 1 – 20 µA (even sub-µA on STM32L/nRF) On wake-up, the chip performs a reset from the start (setup() / main()). The go-to choice for battery sensors.
Hibernation / Shutdown Hibernation / Shutdown Everything off except minimal wake circuit Completely lost Hundreds of ms 0.1 – 5 µA Can only wake from an external button pin or a very basic RTC alarm.

How Does a Microcontroller Wake Up? (Wake-Up Sources)
#

Before putting a chip into Light Sleep or Deep Sleep, you must configure its “alarm clock”—otherwise it will sleep forever until someone presses the reset button:

  • RTC Timer: Wakes periodically (e.g., every 5 minutes or 1 hour).
  • External GPIO (Interrupt): Wakes immediately when a button is pressed, a door opens (reed switch), or an accelerometer detects motion/vibration.
  • ULP (Ultra-Low-Power Co-processor): A special feature on families like the ESP32—a tiny, ultra-efficient processor that stays awake while the main CPU sleeps, polling an ADC or I2C sensor and only waking the main CPU when a reading crosses a threshold.

Preserving Data Across Deep Sleep
#

Because main SRAM is wiped during Deep Sleep, regular variables reset to zero on every wake-up. To retain a cycle counter or temporary queue data without wearing out Flash memory (which has limited write endurance), use RTC Memory (on ESP32, simply add RTC_DATA_ATTR int bootCount = 0;; on STM32, use Backup Registers).


3. Hidden Enemies of Low Power (It’s Not Just Code!)
#

One of the most frustrating moments for beginners is writing spotless Deep Sleep code, measuring the board with a multimeter, and seeing it still draw 10–15 mA instead of 10 µA.

Why does this happen? Because the microcontroller chip isn’t the only thing drinking power—surrounding board components do too:

  1. Power-Hungry Development Boards:

    • Cheap voltage regulators (LDOs): Many dev boards use an AMS1117 regulator whose quiescent current ($I_q$) alone is 5–10 mA! For serious battery designs, pick a low-$I_q$ regulator (such as MCP1700, HT7333, or TPS62740) with $I_q$ under 2 µA.
    • Power LEDs & USB-to-UART Chips: An always-on power indicator LED burns 2–5 mA, plus a CH340/CP2102 bridge chip may keep drawing current even after the USB cable is unplugged.
  2. External Sensors That Never Sleep: Your MCU is sleeping soundly at 10 µA, yet the GPS module, gas sensor, or SD card wired to the 3.3V rail keeps drawing 20 mA all night. The fix is either putting the sensor into its internal sleep mode over I2C/SPI, or physically cutting sensor power using a P-Channel MOSFET / Load Switch IC (Power Gating) before the MCU sleeps.

  3. GPIO Current Leakage & Back-Powering:

    • Unused pins left floating can draw extra leakage current; configure them as analog inputs (on STM32) or isolate them before sleeping.
    • If you cut a sensor’s $V_{CC}$ line with a MOSFET while leaving the MCU’s UART/I2C pins driven HIGH (3.3V), current leaks from those GPIO pins into the sensor through its internal ESD protection diodes (back-powering). Always drive communication lines LOW or High-Z before cutting sensor power.

4. Watchdog Timer (WDT): Your Automatic Guardian Against Firmware Hangs
#

No matter how carefully you write and test your code, an embedded system running 24/7 in the real world will eventually hit the unexpected: an EMI/ESD voltage spike from a nearby electric motor flipping a bit in RAM, a Wi-Fi library stuck forever waiting for a server reply, or an I2C bus lockup caused by a bumped cable.

If your device is mounted on a 20-meter radio tower or in another city, nobody can press the Reset button. This is where the Watchdog Timer (WDT) saves the day.

A simple analogy: A Watchdog Timer works exactly like a Dead Man’s Switch in a train cab. The engineer must press a pedal every few seconds to prove they are still alert. If the engineer passes out and fails to press the pedal before time runs out, the emergency brakes engage automatically for safety.

How a Watchdog Timer Works
#

A Watchdog is an independent hardware counter inside the chip (often clocked by its own independent RC oscillator, so it keeps running even if the main CPU crystal fails).

  1. At startup, firmware enables the WDT with a chosen timeout—for example, 10 seconds.
  2. As long as the firmware is healthy, it periodically resets the WDT counter (popularly called feeding / kicking / petting the dog) before the 10-second countdown expires.
  3. If the program ever gets trapped in an infinite loop, RTOS deadlock, or memory crash, it fails to feed the Watchdog. The counter hits zero, and the WDT hardware immediately forces a Hard Reset so the system automatically recovers.

Three Types of Watchdogs to Know
#

  • Independent Hardware Watchdog (IWDG): The most basic and fault-tolerant type because it runs off a separate clock source.
  • Window Watchdog (WWDG): Stricter—you must not feed it too late, nor too early (feeds must fall within a specific time “window”). Useful in safety-critical systems to detect runaway code looping faster than intended.
  • Task Watchdog (TWDT in RTOS): Monitors the health of individual tasks in FreeRTOS/Zephyr. If a critical task freezes or suffers starvation, the TWDT detects it and logs the offending task’s name before resetting the system.

Combining Watchdog + Deep Sleep (ESP32 Example)
#

Here is a safe pattern combining reset-reason diagnostics, Task Watchdog protection, and Deep Sleep on modern ESP32 toolchains (ESP-IDF / Arduino-ESP32):

#include <Arduino.h>
#include "esp_task_wdt.h"
#include "esp_sleep.h"

#define WDT_TIMEOUT_MS    10000                     // Watchdog timeout: 10 seconds
#define SLEEP_DURATION_US (10ULL * 60 * 1000000ULL) // Sleep for 10 minutes

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

    // 1. Check reset reason for field diagnostics!
    esp_reset_reason_t reason = esp_reset_reason();
    if (reason == ESP_RST_TASK_WDT || reason == ESP_RST_INT_WDT) {
        Serial.println("[ALERT] System just recovered from a Watchdog Reset!");
        // Ideally: log to NVS/Flash or report an error flag to the server
    }

    // 2. Configure & enable Task Watchdog on the current task
    esp_task_wdt_config_t wdt_config = {
        .timeout_ms = WDT_TIMEOUT_MS,
        .idle_core_mask = 0,
        .trigger_panic = true
    };
    esp_task_wdt_reconfigure(&wdt_config);
    esp_task_wdt_add(NULL); // Subscribe the main task

    // 3. Execute main workload (each stage has its own timeout)
    readSensors();
    esp_task_wdt_reset(); // Feed the dog! Sensors OK.

    if (connectWiFiWithTimeout(5000)) {
        esp_task_wdt_reset(); // Feed the dog! Wi-Fi OK.
        sendTelemetryData();
        esp_task_wdt_reset(); // Feed the dog! Transmission complete.
    }

    // 4. Shut down radio/peripherals, then enter Deep Sleep
    Serial.println("Work done. Entering Deep Sleep...");
    Serial.flush();

    esp_sleep_enable_timer_wakeup(SLEEP_DURATION_US);
    esp_deep_sleep_start(); // Execution stops here; wakes up from setup()
}

void loop() {
    // Never reached in a single-cycle Deep Sleep architecture
}

Bonus Power Protection: Brown-Out Detector (BOD)
#

Alongside the Watchdog, modern microcontrollers include a safety feature called a Brown-Out Detector (BOD). When a battery runs low and the Wi-Fi radio suddenly draws a 200 mA spike, the supply voltage can sag momentarily (say, from 3.3V down to 2.2V). If the CPU keeps running at that unsafe voltage, it may execute corrupted instructions or damage Flash contents.

The BOD continuously monitors supply voltage and automatically holds the microcontroller in Reset as soon as voltage dips below a safe threshold—releasing it only once power stabilizes. Avoid the bad habit of disabling BOD just because your power supply is weak; fix the power supply (add bulk capacitance or upgrade the regulator) instead of turning off the safety net!


5 Common Mistakes to Avoid
#

  1. Feeding the Watchdog Inside a Timer Interrupt (ISR) This is the single deadliest WDT mistake. If you put resetWatchdog() inside a periodic Timer ISR, then even when your main loop() freezes completely, the background Timer ISR keeps firing and feeding the Watchdog! The system stays dead forever while the WDT thinks everything is fine. Golden rule: Only feed the Watchdog from the main logic flow after verifying that all subsystems are genuinely healthy.
  2. Setting the WDT Timeout Shorter Than Legitimate Slow Operations If your WDT timeout is 3 seconds while a Wi-Fi/TLS handshake or OTA update can take 8 seconds, your device will get trapped in an endless bootloop. Always calculate worst-case execution times before picking a timeout, and ensure every network call has its own internal timeout.
  3. Using the Watchdog as a Rug to Sweep Bugs Under A Watchdog is an emergency seatbelt, not an excuse to ship code riddled with memory leaks or deadlocks. Always inspect and log the reset reason on boot and include it in telemetry—that way you immediately know if a field unit is silently undergoing Watchdog resets three times a day.
  4. Carelessly Measuring Deep Sleep Current with a Standard Multimeter IoT devices have extreme current dynamic ranges: spiking to 200 mA during Wi-Fi transmission, then dropping to 15 µA in sleep. In µA mode, a standard multimeter’s internal shunt resistor is large enough to cause a severe voltage drop that triggers brown-out resets during boot. For accurate power profiling, use a dedicated tool like the Nordic Power Profiler Kit II (PPK2) or Otii Arc—or wire a bypass switch across your multimeter during boot.
  5. Forgetting Flash Write Endurance When Using Deep Sleep Because every wake-up from Deep Sleep starts the program from scratch, never save a counter that changes every minute to internal Flash/EEPROM (typically rated for only 10,000–100,000 write cycles). Keep temporary state in RTC RAM, and write to Flash only when truly necessary.

You now know how to design firmware that is not only smart, but also energy-efficient and capable of self-recovering from field failures. Yet as we just saw in the Low Power section, even the finest Deep Sleep code is wasted if it still sits on a cheap development board with a leaky regulator and loose jumper wires on a breadboard. In Part 8—the finale of this series—we will step off the breadboard: unpacking minimum-system PCB design fundamentals and professional debugging techniques with serial logs, logic analyzers, and oscilloscopes.

Embedded Systems Fundamentals - This article is part of a series.
Part 7: This Article