Watchdog Timers, Brownout Detection and Fault Recovery for IoT Devices: Designing Firmware That Never Bricks (2026)

Watchdog Timers, Brownout Detection and Fault Recovery for IoT Devices: Designing Firmware That Never Bricks (2026)

Watchdog Timers, Brownout Detection and Fault Recovery for IoT Devices: Designing Firmware That Never Bricks (2026)

A watchdog timer is the cheapest reliability feature on any microcontroller, and in most field fleets it is also the most misused. Teams enable the watchdog timer, drop a refresh call into the main loop or a timer interrupt, and ship. That configuration resets the chip when the CPU stops entirely, which almost never happens. It does nothing when one task deadlocks while the loop keeps spinning, when a brownout corrupts a flash page mid-write, or when a bad update crashes on every boot until the battery dies. With fleets now numbering hundreds of thousands of unattended nodes and truck rolls costing more than the hardware, a device that bricks itself is a business problem, not a debugging anecdote. This guide treats the watchdog timer as one layer of a recovery system that also includes brownout detection, reset-cause telemetry, boot counters and A/B firmware fallback.

What this covers: STM32 IWDG and WWDG timeout math with real LSI tolerances, ESP32 task and interrupt watchdogs, the nRF52 WDT, Zephyr’s watchdog and task watchdog APIs, brownout and power-fail handling, reset-reason telemetry, safe boot counters, MCUboot swap modes and revert, external supervisors, C code for a health-check feeder, failure modes and a deployment checklist.

Context and Background

Every mainstream microcontroller family ships at least one hardware watchdog timer. ST’s STM32 parts carry two watchdog timers: an independent watchdog (IWDG) clocked by the low-speed internal RC oscillator, and a window watchdog (WWDG) clocked from the APB bus. Nordic’s nRF52 series has a single watchdog timer (WDT) with eight independent reload-request registers. Espressif’s ESP32 family exposes several hardware watchdogs through ESP-IDF, which layers a task watchdog and an interrupt watchdog on top of the timer groups and adds an RTC watchdog that guards the bootloader. Real-time operating systems wrap each watchdog timer in portable APIs; Zephyr, for example, provides both a generic watchdog driver interface and a software “task watchdog” that multiplexes many logical channels onto one hardware timer.

Brownout detection is the watchdog timer’s sibling. A brownout reset (BOR) circuit holds the core in reset when the supply falls below a threshold, so that the CPU never executes instructions at a voltage where flash reads, PLL lock or SRAM retention are unreliable. Many parts add an earlier warning stage, such as Nordic’s power-fail comparator or ST’s programmable voltage detector, that interrupts the firmware before the hard reset.

The third piece is the bootloader. MCUboot, the open-source secure bootloader used by Zephyr, Nordic’s nRF Connect SDK, Trusted Firmware-M and several vendor SDKs, can test-boot a new image and revert automatically if the image never confirms itself. ESP-IDF has an equivalent rollback state machine for its OTA partitions. Our comparison of SUIT, Uptane, Mender, RAUC and SWUpdate covers the update frameworks above this layer; this post is about what happens on the device when things go wrong.

What existing material rarely does is connect these pieces. Vendor application notes explain one peripheral at a time. The thesis here is that embedded fault recovery is a pipeline: detect (watchdog, brownout), contain (reset into a known state), diagnose (reset cause plus breadcrumbs), and escape (boot counter, revert, safe mode). A device never bricks only if every stage works and each stage assumes the one before it may fail. The Espressif watchdog documentation is a good primary reference for how one vendor stacks several watchdogs, and we will use it alongside ST, Nordic and Zephyr sources throughout.

Reference Architecture: A Layered Watchdog Timer Strategy for IoT Device Reliability

A robust watchdog timer design feeds the hardware watchdog only from a health-supervisor task that confirms every critical task made progress within its deadline. An independent watchdog clocked from a separate oscillator catches total hangs, brownout detection prevents execution at unsafe voltage, and a bootloader boot counter escapes crash loops by reverting firmware or entering safe mode.

Layered watchdog timer architecture with health supervisor, internal and external watchdogs, brownout reset and bootloader fallback
Figure 1: Layered fault-recovery architecture. Tasks report to a health supervisor; only the supervisor feeds the internal watchdog and an optional external supervisor; every reset path converges on a bootloader that counts boots and records reset causes.

Figure 1 shows the flow from top to bottom. Application tasks never touch the watchdog timer. Each one checks in with a health supervisor, which feeds the internal watchdog only when every registered task has advanced. An external supervisor IC with its own oscillator and voltage monitor sits beside the MCU as an optional last line. All reset sources, whether watchdog, external supervisor or brownout, converge on the bootloader. The bootloader reads the reset cause, maintains a boot counter in memory that survives a warm reset, and decides whether to boot normally, revert an update or enter a safe mode. The reset cause and any breadcrumbs then travel to fleet telemetry.

Independent versus window watchdog: what each actually catches

The STM32 independent watchdog runs from the LSI oscillator, so it keeps counting even if the main clock tree, the PLL or the HSE crystal fails. ST’s training material for the STM32G4 describes it as a 12-bit down-counter behind a prescaler that divides the roughly 32 kHz LSI by 4 up to 256, giving timeouts from about 125 microseconds to about 32 seconds. It can be started by software or, through the hardware-watchdog option byte, automatically at every reset with no firmware involvement at all. That last property matters: a hardware-started IWDG protects even the window between reset and the first line of main().

The window watchdog is clocked from PCLK1 through a fixed divide-by-4096 prescaler and a small additional divider. Its distinctive feature is a lower bound. Refreshing too early, before the counter drops below the programmed window value, triggers a reset just as surely as refreshing too late. That catches a class of bug the independent watchdog cannot: a runaway loop that happens to call the refresh function far too often. The cost is that the WWDG depends on the main clock, so it cannot detect a clock failure, and its maximum timeout is tens of milliseconds rather than seconds.

The practical conclusion is to use the independent watchdog IWDG as the always-on safety net with a timeout of one to a few seconds, and reserve the WWDG for tight control loops where timing correctness, not just liveness, is the requirement.

Feed from a health-check task, never from an interrupt or the idle loop

The most common watchdog timer anti-pattern is feeding from a periodic timer interrupt. Interrupts keep firing even when every thread is deadlocked, so the watchdog timer never expires. Feeding from the main loop is barely better on an RTOS, because one task can be stuck on a mutex forever while the loop that feeds keeps running.

The fix is a health supervisor. Each critical task registers with a deadline and periodically reports progress, ideally a counter that only advances when real work completes, not merely “I was scheduled”. The supervisor runs at a period well inside the hardware timeout, checks every registered task, and feeds only if all are healthy. If any task misses, the supervisor stops feeding, writes the culprit’s identifier into retained RAM, and lets the hardware reset the chip. This converts “the device rebooted” into “the device rebooted because the comms task stopped advancing”, which is the difference between a guess and a fix.

Zephyr ships this pattern as a subsystem. Its task watchdog uses kernel timers to give each thread its own channel, with an optional hardware watchdog as a fallback in case the scheduler itself fails. ESP-IDF’s task watchdog follows the same idea: tasks subscribe with esp_task_wdt_add() and each must call esp_task_wdt_reset() before the timeout, and the idle task on each core is subscribed by default to detect CPU starvation.

Brownout detection is the other half of the watchdog

A watchdog timer assumes the CPU executes instructions correctly but slowly. A brownout breaks that assumption. Below the rated voltage, flash reads can return wrong values and a CPU can execute garbage. A watchdog cannot fix that, because the code that should feed or not feed it is itself unreliable.

Brownout detection therefore belongs in the same design review as the watchdog timer. The BOR threshold must sit above the minimum operating voltage of everything the MCU depends on at its configured clock speed, including external flash. An early-warning comparator should give the firmware time to finish or abandon flash writes before the hard reset. We return to the mechanics, with numbers, in the brownout section below.

Walk-through: Timeout Math, Feeder Code, Reset Telemetry and Boot Counters

This section works through the numbers and code a firmware team actually needs: how to size a watchdog timer timeout against a clock that can be off by tens of percent, how to write the supervisor, how to capture reset causes, and how a boot counter plus an A/B bootloader escapes a crash loop.

Worked watchdog timer math: STM32 IWDG

The IWDG counts down from the reload value at the LSI frequency divided by the prescaler. The timeout is:

t = (4 × 2^PR × (RL + 1)) / f_LSI

where PR is the 3-bit prescaler code (0 means divide-by-4, 6 means divide-by-256) and RL is the 12-bit reload value (0 to 4095). The STM32F411 reference manual’s IWDG timing table, computed at 32 kHz, confirms the formula: divide-by-4 with RL at 0xFFF gives 512 ms, and divide-by-256 gives 32,768 ms.

Suppose the target nominal timeout is 2 seconds. Choose PR = 3 (divide-by-32). At 32 kHz the counter ticks at 1,000 Hz, so RL = 1999 gives exactly 2.000 s nominal.

Now apply the real oscillator tolerance. The LSI is an uncalibrated RC oscillator. In an ST community thread on IWDG timeout accuracy for an STM32F446, contributors citing the device datasheet give an LSI range of roughly 17 kHz to 47 kHz around a 32 kHz nominal. Check your own part’s datasheet, because the range varies by family. With that range, the 2-second design actually expires anywhere between:

  • 2.0 × 32 / 47 ≈ 1.36 s (fast LSI)
  • 2.0 × 32 / 17 ≈ 3.76 s (slow LSI)

The watchdog timer design rule follows directly. The supervisor must feed comfortably inside the shortest possible timeout, so a 500 ms supervisor period leaves almost a second of margin at worst case. Recovery latency is bounded by the longest timeout, so a hung device may sit unresponsive for nearly four seconds before resetting. If either bound is unacceptable, measure the actual LSI at startup with a timer input capture against the crystal-derived clock, as ST’s own examples do, and compute RL from the measured frequency.

Worked timeout math: STM32 WWDG

The window watchdog on the STM32F401, per its reference manual, follows:

t_WWDG = t_PCLK1 × 4096 × 2^WDGTB × (T[5:0] + 1)

The 7-bit counter starts at 0x7F and resets the chip when it rolls from 0x40 to 0x3F. An early-wakeup interrupt can fire at 0x40, one tick before the reset, for last-gasp logging.

Take PCLK1 at 42 MHz and WDGTB = 3 (divide-by-8). One counter tick is 4096 × 8 / 42,000,000 ≈ 0.78 ms. With the counter loaded to 0x7F (T[5:0] = 63), the reset arrives after 64 ticks, about 49.9 ms. Set the window register to 0x50. Refreshing is now illegal until the counter has dropped from 0x7F to below 0x50, which is 47 ticks or about 36.6 ms. The legal refresh window is therefore roughly 36.6 ms to 49.9 ms after the previous refresh: a 13 ms slot.

That narrow slot is the point. A control loop that is supposed to run every 40 ms can feed the WWDG at the end of each iteration. If a bug makes the loop run every 5 ms, the early refresh resets the chip. If a stall makes it run every 60 ms, the late refresh resets the chip. Note that the same reference manual’s worked example appears inconsistent with its own formula, a point raised on ST’s community forum, so compute timeouts yourself rather than copying the example.

nRF52 WDT and ESP32 watchdog timers in numbers

Nordic’s nRF52840 product specification defines the WDT timeout as (CRV + 1) / 32768 seconds, running from the 32.768 kHz low-frequency clock. A 2-second timeout needs CRV = 65,535. The unusual feature is the eight reload-request registers, RR[0] to RR[7]. When several are enabled, the counter reloads only after every enabled register has received the magic value 0x6E524635. That is a hardware implementation of the health-supervisor idea: assign one RR register per critical task and the silicon refuses to reload until all of them check in. Once started, the WDT configuration registers are locked until reset, and the documentation lists only a start task, not a stop task. A TIMEOUT event can trigger an interrupt, but the reset follows two 32.768 kHz cycles later and cannot be cancelled, which is enough time to set a flag in retained RAM but not to flush a log to flash.

Espressif’s ESP-IDF layers watchdogs differently. According to the current Kconfig reference for the ESP32:

Watchdog Kconfig Default What it detects
Interrupt watchdog CONFIG_ESP_INT_WDT_TIMEOUT_MS 300 ms, or 800 ms with PSRAM; range 10 to 10,000 Interrupts blocked too long on a core
Task watchdog CONFIG_ESP_TASK_WDT_TIMEOUT_S 5 s; range 1 to 60 Subscribed tasks or idle tasks not running
Task watchdog panic CONFIG_ESP_TASK_WDT_PANIC Disabled Whether a task watchdog timeout resets the chip
Bootloader RTC watchdog CONFIG_BOOTLOADER_WDT_TIME_MS 9,000 ms; range 0 to 120,000 Hangs during startup

The third row is the gotcha that bites production ESP32 fleets. By default the task watchdog prints a warning and a backtrace and keeps running. A device stuck in an infinite loop in a subscribed task will log forever without resetting unless the panic option is enabled. Production builds should enable CONFIG_ESP_TASK_WDT_PANIC and configure the panic handler to reboot.

The interrupt watchdog is fed by each core’s FreeRTOS tick interrupt, so it catches long critical sections and interrupt storms, not task-level stalls. The two are complementary, not redundant.

C code: a health supervisor that feeds only when every task progressed

The following example uses Zephyr’s task watchdog for per-task channels, a hardware watchdog as fallback, and retained RAM for breadcrumbs. It compiles against current Zephyr APIs (task_wdt_init, task_wdt_add, task_wdt_feed, hwinfo_get_reset_cause), but treat the retained-RAM section name and stack sizes as board-specific placeholders.

#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/task_wdt/task_wdt.h>
#include <zephyr/drivers/hwinfo.h>
#include <zephyr/sys/reboot.h>

/* Breadcrumbs survive a warm reset if placed in a no-init region.
 * The section name is board/linker specific. */
struct crash_crumbs {
    uint32_t magic;
    uint32_t boot_count;
    uint32_t last_stalled_channel;
    uint32_t last_reset_cause;
};
__attribute__((section(".noinit"))) static struct crash_crumbs crumbs;
#define CRUMB_MAGIC 0xB007C0DE

static const struct device *hw_wdt = DEVICE_DT_GET(DT_ALIAS(watchdog0));

static void on_task_stall(int channel_id, void *user_data)
{
    /* Runs from the task_wdt timer context: keep it tiny. */
    crumbs.last_stalled_channel = (uint32_t)channel_id;
    sys_reboot(SYS_REBOOT_COLD);
}

static int sensor_ch, comms_ch;

static void sensor_thread(void)
{
    sensor_ch = task_wdt_add(2000, on_task_stall, NULL);
    while (1) {
        if (read_and_publish_sample() == 0) {   /* real work done */
            task_wdt_feed(sensor_ch);            /* progress, not presence */
        }
        k_sleep(K_MSEC(500));
    }
}

static void comms_thread(void)
{
    comms_ch = task_wdt_add(30000, on_task_stall, NULL);
    while (1) {
        int rc = mqtt_service_once(K_MSEC(1000));
        if (rc >= 0) {
            task_wdt_feed(comms_ch);
        }
    }
}

void boot_diagnostics(void)
{
    uint32_t cause = 0;
    hwinfo_get_reset_cause(&cause);
    hwinfo_clear_reset_cause();      /* flags may be cumulative */

    if (crumbs.magic != CRUMB_MAGIC) {   /* cold boot: RAM was garbage */
        crumbs = (struct crash_crumbs){ .magic = CRUMB_MAGIC };
    }
    crumbs.boot_count++;
    crumbs.last_reset_cause = cause;

    /* Queue for upload once the network is up. */
    telemetry_enqueue_reset(cause, crumbs.last_stalled_channel,
                            crumbs.boot_count);
    crumbs.last_stalled_channel = UINT32_MAX;
}

int main(void)
{
    boot_diagnostics();
    /* Hardware fallback catches a dead scheduler or a dead task_wdt timer. */
    task_wdt_init(device_is_ready(hw_wdt) ? hw_wdt : NULL);
    /* threads started via K_THREAD_DEFINE elsewhere */
    return 0;
}

Three details carry the design. First, each task feeds only after completing real work, so a task that spins without making progress still trips its channel. Second, channel timeouts differ: a cellular comms task that legitimately waits through network attach gets 30 seconds, while the sensor loop gets two. Third, the hardware watchdog sits underneath as a fallback, so a corrupted kernel timer list cannot silently disable supervision.

On bare metal or FreeRTOS, the same pattern is a supervisor task holding an array of {last_progress_tick, deadline} entries. It loops every 500 ms, compares each entry against the current tick, and writes the reload key (0xAAAA for the STM32 IWDG) only if all entries are fresh.

Sequence of tasks checking in to a health supervisor that stops feeding the watchdog timer when a task stalls
Figure 2: Health-supervisor feeding sequence. The supervisor feeds only after every task has advanced; a stalled task causes the supervisor to record the culprit and withhold the feed.

Figure 2 traces a failure. Both tasks check in during the first period and the supervisor feeds. In the next period the comms task blocks on a mutex. The supervisor notices the missed deadline, records the channel in retained RAM, and stops feeding. The hardware watchdog timer expires and resets the chip, and the bootloader reads the breadcrumb on the next boot.

Reset-reason telemetry: making every reboot explainable

A reset you cannot classify is a reset you cannot fix. Every MCU exposes reset-cause flags, and every one has quirks.

On STM32, the RCC control-and-status register holds flags for low-power, window watchdog, independent watchdog, software, power-on, pin and, on many families, brownout resets. Two quirks matter. The flags persist until firmware clears them with the remove-flags bit, so a device that never clears them reports a growing union of every cause since power-on. And because internal resets are driven out on the NRST pin, the pin-reset flag is typically set alongside the real cause; decode by priority, not by “first flag set”.

On the nRF52832, the RESETREAS register has fields for pin reset, watchdog (DOG), soft reset (SREQ), CPU lockup and several wake-from-System-OFF sources. The register is cumulative and cleared by writing ones. There is no explicit brownout or power-on flag: if no field is set, the reset came from the on-chip reset generator, meaning power-on or brownout. ESP-IDF abstracts all of this into esp_reset_reason(), whose enum distinguishes ESP_RST_INT_WDT, ESP_RST_TASK_WDT, ESP_RST_WDT, ESP_RST_PANIC, ESP_RST_BROWNOUT, ESP_RST_POWERON and others. Zephyr’s hwinfo_get_reset_cause() returns portable bits such as RESET_WATCHDOG, RESET_BROWNOUT, RESET_POR, RESET_CPU_LOCKUP and RESET_SOFTWARE, and its documentation warns that some platforms accumulate flags until cleared.

The telemetry record worth sending on every boot is small: reset cause, boot counter, firmware version, uptime before the reset if you track it in retained RAM, stalled-task channel if any, and for panics, the program counter and link register. Fleet dashboards can then compute meaningful metrics:

  • Unexpected resets per 1,000 device-days, split by cause. Planned resets after OTA or by command are excluded.
  • Watchdog timer resets per firmware version, which turns a release regression into a visible step change.
  • Brownout resets by site or battery age, which usually point at hardware, not code.
  • Crash-loop count: devices whose boot counter exceeded the safe-mode threshold.

As an illustrative example, not measured data: if a 50,000-device fleet averages 0.2 unexpected resets per 1,000 device-days, that is about 10 resets a day fleet-wide. A new firmware version that doubles the watchdog-cause share is obvious within one day of a 10 percent staged rollout. Without cause decoding, those 10 events are noise.

Boot counters and A/B fallback with MCUboot

The watchdog timer guarantees a reset; it does not guarantee the next boot will be any better. A firmware image that crashes 800 ms after every boot produces an infinite reboot loop, perfectly supervised and completely useless. The escape is a boot counter combined with an A/B bootloader.

Boot decision flow using reset cause, boot counter and MCUboot revert for embedded fault recovery
Figure 3: Boot-time decision flow. A boot counter in retained RAM detects crash loops; an unconfirmed update is reverted by MCUboot, and a confirmed image that still loops falls back to a safe mode.

Figure 3 shows the logic. On every reset the early boot code reads and clears the reset cause and increments a counter. When the counter exceeds a limit, say five consecutive boots without reaching the “healthy” milestone, two escapes exist. If a new image is still unconfirmed, the bootloader reverts to the previous slot. If the running image was already confirmed, firmware enters a safe mode that brings up only the minimal network stack needed to report status and accept a new update. The counter is cleared only after the self-test passes and the image is confirmed.

MCUboot supports this natively. Its design documentation lists the upgrade strategies: overwrite-only, swap-using-scratch, swap-using-move, swap-using-offset, direct-XIP and RAM-load. In the swap modes, a test upgrade boots the new image once; if the image does not set its image-ok flag before the next reset, MCUboot performs a revert swap and restores the old image. A permanent upgrade sets image-ok at swap time and never reverts. The documentation notes that swap-using-offset is now preferred over swap-using-move for new designs and that swap-using-scratch may be removed in future. Direct-XIP and RAM-load support revert through dedicated options and require padded images. Overwrite-only cannot revert at all, because the old image is gone once copied over.

Swap progress is recorded in a status region, so a reset in the middle of a swap resumes from the last recorded step on the next boot. That is precisely the property you need when a watchdog or brownout interrupts the bootloader itself. Long swaps take time, so the bootloader must feed the watchdog timer; MCUboot’s Zephyr port provides a BOOT_WATCHDOG_FEED option and a MCUBOOT_WATCHDOG_FEED() hook that the swap code calls during long operations. If the hook compiles to a no-op on your platform and a hardware-started watchdog is running, a large swap can be interrupted repeatedly. The resume logic keeps the device consistent, but the update never finishes.

On Zephyr, the application confirms itself with boot_write_img_confirmed() after its self-test. On ESP-IDF, with CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE set, a new image boots in the ESP_OTA_IMG_PENDING_VERIFY state and must call esp_ota_mark_app_valid_cancel_rollback(). Espressif’s documentation is explicit that a reset before confirmation, whether from a watchdog, a crash or a power loss, marks the image aborted and rolls back. That makes the watchdog timer an integral part of the update path: a new image that hangs is reset by the watchdog and the reset itself triggers the rollback.

What should the self-test check? At minimum: the network stack attached and reached the update server, the main sensors returned plausible data, and the device survived a few minutes of normal operation. Confirming too early, at the top of main(), defeats the purpose. Confirming too late on a battery device that sleeps for hours risks a spurious rollback from an unrelated power event. Our guide to cellular IoT power saving with PSM and eDRX explains why network attach can legitimately take far longer than a lab test suggests, which should inform both the comms-task watchdog deadline and the confirmation timeout.

Brownout Detection and Power-Fail-Safe Flash Writes

Brownout handling has three parts: a hard reset threshold, an early warning, and a storage format that tolerates a write being cut off at any byte.

The hard threshold differs by vendor. STM32 parts set the BOR level through option bytes, with several selectable thresholds documented in each device’s datasheet. ESP-IDF’s Kconfig for the ESP32 offers eight brownout levels from about 2.43 V to 2.80 V, each listed as plus or minus 0.05 V, and notes that these are estimates that vary between chips. The nRF52832 holds the system in reset below its brownout threshold and offers a separate power-fail comparator whose threshold is configurable from 1.7 V to 2.8 V in 0.1 V steps. Pick a threshold above the worst-case minimum voltage of every component on the same rail at the operating clock frequency, not merely the MCU’s absolute minimum.

The early warning is where firmware can act. On the nRF52, the POFWARN event fires when supply drops below the comparator threshold, and when the warning is enabled and supply is below that level, the comparator also blocks NVMC writes to non-volatile memory. That hardware interlock is valuable, but it means a write already in progress may complete while the next one is refused. Firmware must treat a refused write as a normal outcome, not an error to retry in a tight loop.

Brownout detection sequence with power-fail warning, flash journal protection, brownout reset and recovery validation
Figure 4: Brownout sequence. The power-fail warning gives firmware time to finish the current flash record and park loads; the brownout reset holds the core until the rail recovers; boot validates the journal and discards any torn record.

Figure 4 shows the sequence. The rail sags, the comparator interrupts, and the firmware finishes the current flash record without starting a new erase. It also parks high-current loads such as the radio or a motor driver, which often buys more hold-up time than anything else. If the rail keeps falling, BOR holds the core in reset. When it recovers above threshold plus hysteresis, the chip boots and validates the journal.

How much time does the warning buy? It is a hold-up capacitance calculation. For a roughly constant load current, t ≈ C × ΔV / I. Illustrative numbers: if the warning threshold is 2.9 V, the BOR threshold is 2.7 V, and the device draws 15 mA with the radio off, then 220 µF of bulk capacitance gives about 220e-6 × 0.2 / 0.015 ≈ 2.9 ms. That is enough to finish programming a few words but not to erase a sector, which on many MCUs takes tens to hundreds of milliseconds (check your datasheet’s flash timing table). The design implication is clear: never start an erase when the warning is active, and design storage so that an erase interrupted at any moment is harmless.

Power-fail-safe storage follows a few rules. Use append-only records with a sequence number and CRC, so a torn final record is detected and ignored. Keep two copies of critical configuration and switch between them atomically by sequence number. Never erase the only valid copy. Prefer the vendor’s or RTOS’s wear-levelled, power-safe key-value store, such as Zephyr’s NVS or ZMS or ESP-IDF’s NVS library, over hand-rolled schemes, and test them with real power cuts, not just simulated resets. The Rust no_std embedded firmware guide covers how type-level ownership can make these “write only from one place” rules harder to violate.

External Supervisors: When the Internal Watchdog Is Not Enough

An internal watchdog timer shares silicon, power and sometimes clock with the thing it supervises. A latch-up, a corrupted option byte that disables the hardware watchdog, or a flash read failure that executes a “disable” path can defeat it. External supervisor ICs exist for exactly this reason.

Texas Instruments’ TPS3823, a typical example, is a voltage supervisor with a watchdog input, a manual reset input and a push-pull active-low reset output in a five-pin SOT-23 package. TI’s product page lists a 1.6-second watchdog timeout, a fixed 200 ms reset delay, about 15 µA typical supply current, and several fixed threshold voltages from about 2.25 V to 4.55 V. The MCU must toggle the watchdog input pin within the timeout or the supervisor pulls reset. Because the supervisor monitors the rail itself, it also provides a brownout reset that does not depend on the MCU’s internal BOR.

Three design choices matter. Drive the watchdog input from the health supervisor, exactly like the internal watchdog timer, never from a timer peripheral that toggles autonomously. Confirm that a 1.6-second timeout is longer than your worst-case bootloader path, including a full MCUboot swap, or provide a way for the bootloader to toggle the pin. And remember the supply current: 15 µA is negligible on mains power but material on a coin-cell device designed for multi-year life, where the whole sleep budget may be single-digit microamps. Some supervisor families offer a watchdog-disable input or a much longer timeout for such designs.

Trade-offs, Gotchas, and What Goes Wrong

Feeding in a loop masks deadlock. Covered above, but it is the root cause of most “the watchdog timer didn’t fire” incidents. Any feed path that does not depend on every critical task making progress is decorative.

Debug builds and production builds diverge. ST, Nordic and Zephyr all provide options to freeze the watchdog while a debugger halts the core, and Espressif’s documentation notes that OpenOCD disables both ESP-IDF hardware watchdogs at each breakpoint and does not re-enable them. Teams that develop with the watchdog timer effectively off ship code whose timing has never been tested against it. Run soak tests with the debugger detached and the watchdog timer fully armed.

Flash wear from reboot loops. A boot counter stored in internal flash and erased on every boot is a time bomb. Illustrative arithmetic: if a sector is rated for around 10,000 erase cycles (a common order of magnitude; check your datasheet) and a crash loop reboots every three seconds, a naive erase-per-boot scheme wears out that sector in about 30,000 seconds, roughly eight hours. Store the counter in retained RAM or a backup register, which survives warm resets for free, or append to a flash log so one erase covers hundreds of boots.

Brownout during flash write. Without a power-fail warning and a journaled format, a brownout mid-write corrupts configuration, and the next boot may crash on the corrupted data, creating a crash loop that only a boot counter can break.

Reset-cause misreads. Not clearing cumulative flags, or trusting the pin-reset flag, produces telemetry that blames the wrong subsystem. Read once, clear immediately, decode by priority.

Timeouts sized for the lab. Cellular attach, TLS handshakes over a congested link, or a large flash erase can exceed a watchdog deadline that looked generous on the bench. Give long-blocking tasks their own longer channels rather than stretching the global watchdog timer.

Low-power modes. An IWDG that keeps running in Stop mode will reset a device that sleeps longer than the timeout. Either freeze it in low-power modes through the option bits, which weakens protection, or wake periodically to feed, which costs energy. Nordic’s WDT CONFIG register exposes the same choice for sleep.

Safe mode that is not safe. A safe mode that initialises the same driver that crashed the main image just loops more slowly. Keep safe mode minimal and test it as a first-class build.

Practical Recommendations

Treat watchdog timer design as a reviewed artifact, with written timeouts, feed paths and recovery behaviour, not a line of code added at the end. Size every timeout against oscillator tolerance and against the slowest legitimate operation, and make the supervisor’s period a fraction of the shortest possible expiry. Wire reset causes into telemetry before the first field pilot, because the first unexplained reboot will otherwise stay unexplained.

On the update side, never ship a bootloader configuration that cannot revert. Use MCUboot test swaps or ESP-IDF rollback, confirm only after a meaningful self-test, and make sure the bootloader feeds whichever watchdog timer is running during long swaps. Then test the unhappy paths deliberately: pull power during an update, hang a task with a debug command, flash an image that crashes on boot, and confirm the device returns to a working image without a technician. This is the core of IoT device reliability: recovery behaviour that has been exercised, not merely designed. For the broader update pipeline, see our secure IoT OTA firmware update architecture.

Checklist before shipping:

  • [ ] Independent watchdog timer enabled, ideally hardware-started via option bytes or equivalent.
  • [ ] Watchdog fed only by a health supervisor that checks per-task progress.
  • [ ] Timeouts computed at worst-case oscillator tolerance, with margins written down.
  • [ ] ESP32 builds: CONFIG_ESP_TASK_WDT_PANIC enabled for production.
  • [ ] BOR threshold above every component’s minimum voltage; power-fail warning wired to stop new erases.
  • [ ] Reset cause read, cleared and uploaded on every boot, with breadcrumbs in retained RAM.
  • [ ] Boot counter in retained RAM or an append-only log, never erase-per-boot.
  • [ ] Bootloader revert tested; bootloader feeds the watchdog during swaps.
  • [ ] Minimal safe mode that can still receive an update.
  • [ ] Power-cut, hang and crash-on-boot tests run on production hardware with no debugger attached.

Frequently Asked Questions

What is a watchdog timer in an IoT device?

A watchdog timer is a hardware counter that resets the microcontroller unless firmware periodically refreshes it. If software hangs, deadlocks or runs away, the refresh stops and the chip resets into a known state. In IoT devices that operate unattended for years, it is the primary mechanism for recovering from software faults without a site visit. Its effectiveness depends entirely on what code refreshes it: a refresh that only proves an interrupt is firing provides little protection, while one gated on every task’s progress catches most real failures.

What is the difference between the STM32 IWDG and WWDG?

The independent watchdog runs from the low-speed internal oscillator, so it survives main clock failures and supports timeouts from about 125 microseconds to about 32 seconds. It only checks that a refresh happened before expiry. The window watchdog runs from the APB clock, has timeouts in the tens of milliseconds, and also resets the chip if firmware refreshes too early. Use the IWDG as the always-on liveness check and the WWDG for timing-critical control loops where a loop running too fast is as dangerous as one running too slowly.

Why should I not feed the watchdog timer from a timer interrupt?

Interrupts continue firing when application threads are deadlocked, blocked on a mutex, or stuck in a retry loop. A watchdog timer fed from a timer interrupt therefore resets the device only when the CPU stops completely, which is the rarest failure in practice. Feed the watchdog timer instead from a health-supervisor task that checks each critical task has made real progress within its deadline. Zephyr’s task watchdog, ESP-IDF’s task watchdog and the nRF52’s multiple reload registers all exist to support this per-task supervision pattern.

How does brownout detection protect flash memory?

A brownout reset holds the processor in reset when supply voltage drops below a threshold, preventing execution at voltages where flash reads or writes are unreliable. Many MCUs also offer an earlier warning comparator that interrupts firmware before the hard reset; on Nordic nRF52 parts, that comparator can also block further non-volatile memory writes. Firmware should use the warning to finish the current record and avoid starting erases, and store data in journaled records with sequence numbers and CRCs so a torn write is detected and discarded on the next boot.

How do I stop a bad firmware update from causing an endless reboot loop?

Combine three mechanisms. Use a bootloader that test-boots new images and reverts unless the image confirms itself, such as MCUboot test swaps or ESP-IDF app rollback. Confirm only after a self-test that proves networking and core functions work. Then keep a boot counter in retained RAM, incremented on every reset and cleared after confirmation; if it exceeds a threshold, revert or enter a minimal safe mode that can still download a fix. The watchdog timer guarantees the reset, and the bootloader guarantees the reset leads somewhere better.

Do I need an external watchdog timer if my MCU has one built in?

Not always, but it is worth considering for devices that are expensive to reach or safety-relevant. An internal watchdog shares power, silicon and sometimes configuration with the processor it supervises, so a latch-up, corrupted option bytes or a supply problem can defeat it. An external supervisor such as TI’s TPS3823 has its own timing and voltage monitoring. The trade-offs are board space, a fixed timeout that must exceed worst-case bootloader time, and quiescent current that matters on coin-cell designs.

Further Reading

By Riju — about

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *