What is STM32F407 Watchdog Timers-Embedded C Programming Training Online

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Tutorial 22 — System Reliability

STM32F407 Watchdog Timers

Master the Independent Watchdog (IWDG) and Window Watchdog (WWDG) — registers explained bit-by-bit, timeout formulas, the crucial difference between them, and practical bare-metal C code for robust embedded systems.

IWDG Independent WDGWWDG Window WDGLSI ~32kHz clockHardware Cannot disable once startedReset On timeout or early kick

01 Overview & Comparison

A watchdog timer automatically resets the microcontroller if the software fails to “kick” (refresh) it within a configured timeout. This recovers from software hangs, infinite loops, stack overflows, and unexpected faults.

FeatureIWDG (Independent)WWDG (Window)
Clock sourceLSI (~32 kHz, independent of main clock)PCLK1 (42 MHz, APB1)
Timeout range0.125ms – 32.77s (prescaled)~113µs – ~58ms
Window checkNo — kick any time before timeoutYes — kick too early ALSO resets!
Early kick resetNoYes (if kicked in forbidden window)
Debug stopCan freeze in debug via DBG_IWDG_STOPCan freeze in debug via DBG_WWDG_STOP
Stops in Stop/StandbyNo — continues running on LSIYes — stops with PCLK1
Once startedCannot be stopped (only reset)Cannot be stopped (only reset)
Base address0x400030000x40002C00
APB busAPB1 (but clocked by LSI)APB1
Use caseGeneral fault recovery, long timeoutsTiming-critical code — detects both too-slow AND too-fast execution
Hardware one-way latch: Once you start either watchdog, it runs until the next system reset. There is no software disable. Design your kick strategy before enabling.

02 IWDG — Independent Watchdog

The IWDG uses the LSI (Low-Speed Internal) RC oscillator at ~32 kHz — completely independent of HSE, HSI, and PLL. Even if your main clock fails, the IWDG keeps ticking and resets the chip. It survives Stop and Standby modes.

IWDG Registers

OffsetRegisterKey BitsPurpose
0x00IWDG_KR[15:0] KEYWrite-only key register: 0xCCCC=start, 0xAAAA=reload (kick), 0x5555=unlock PR/RLR
0x04IWDG_PR[2:0] PRPrescaler: 0=÷4, 1=÷8, 2=÷16, 3=÷32, 4=÷64, 5=÷128, 6=÷256. Write after KR=0x5555.
0x08IWDG_RLR[11:0] RLReload value (0–4095). Counter counts down from RL to 0 then resets. Write after KR=0x5555.
0x0CIWDG_SRPVU(0), RVU(1)Status: PVU=PR update busy, RVU=RLR update busy. Wait for these to clear before verifying.

Timeout formula:

Timeout = (4 × 2PR × (RL+1)) / LSI_Hz

With LSI = 32000 Hz (nominal; actual can be 17–47 kHz — use RTC to calibrate):

PRPrescalerMin timeout (RL=0)Max timeout (RL=4095)
0÷40.125 ms512 ms
1÷80.25 ms1.024 s
2÷160.5 ms2.048 s
3÷321 ms4.096 s
4÷642 ms8.192 s
5÷1284 ms16.384 s
6÷2568 ms32.768 s

IWDG Timeout Calculator

IWDG Timeout Calculator

32000
3 (÷32)
2499
Prescaler divisor: 32
Timeout = (32 × 2500) / 32000 Hz = 2500.00 ms
C code: IWDG_Init(3, 2499);

IWDG Bare-Metal Code

C — IWDG with configurable timeout

#include <stdint.h>

#define IWDG_BASE  0x40003000UL
#define IWDG_KR    (*(volatile uint32_t *)(IWDG_BASE+0x00))
#define IWDG_PR    (*(volatile uint32_t *)(IWDG_BASE+0x04))
#define IWDG_RLR   (*(volatile uint32_t *)(IWDG_BASE+0x08))
#define IWDG_SR    (*(volatile uint32_t *)(IWDG_BASE+0x0C))

#define IWDG_KEY_RELOAD  0xAAAAU
#define IWDG_KEY_START   0xCCCCU
#define IWDG_KEY_UNLOCK  0x5555U

/* Initialize IWDG for ~2.5s timeout
   PR=3 (÷32), RL=2499:
   Timeout = (4×8×2500)/32000 = 2.5s */
void IWDG_Init(uint8_t prescaler, uint16_t reload) {
    /* Step 1: Unlock write to PR and RLR */
    IWDG_KR = IWDG_KEY_UNLOCK;

    /* Step 2: Wait for any previous update to finish */
    while (IWDG_SR & 0x3);  /* wait PVU=0 and RVU=0 */

    /* Step 3: Set prescaler */
    IWDG_PR = prescaler & 0x7;

    /* Step 4: Set reload value */
    IWDG_RLR = reload & 0xFFF;

    /* Step 5: Wait for values to be loaded */
    while (IWDG_SR & 0x3);

    /* Step 6: Reload counter */
    IWDG_KR = IWDG_KEY_RELOAD;

    /* Step 7: Start watchdog — CANNOT BE STOPPED after this */
    IWDG_KR = IWDG_KEY_START;
}

/* Kick watchdog — MUST be called within timeout period */
void IWDG_Kick(void) {
    IWDG_KR = IWDG_KEY_RELOAD;  /* writes 0xAAAA */
}

/* ──────────────────────────────────────────────────
   Example: 2.5s watchdog, kicked in main loop
   If system hangs for >2.5s, hardware reset occurs
────────────────────────────────────────────────── */
void do_work(void);  /* forward declaration */

int main(void) {
    SystemInit();

    /* Initialize IWDG: PR=3 (÷32), RL=2499 → ~2.5s */
    IWDG_Init(3, 2499);

    while (1) {
        do_work();          /* must complete in <2.5s */
        IWDG_Kick();        /* pet the watchdog */
    }
}

/* Example with RTOS-style task checkpoint */
volatile uint32_t task_checkins = 0;
#define TASK_COUNT  3

void task_checkin(uint8_t task_id) {
    task_checkins |= (1 << task_id);
    if (task_checkins == (((1<<TASK_COUNT)-1))) {
        /* All tasks checked in — safe to kick */
        IWDG_Kick();
        task_checkins = 0;
    }
}

03 WWDG — Window Watchdog

The Window Watchdog adds a minimum time constraint: you must kick it within a specific window — not too late (normal watchdog behavior) AND not too early. Kicking too early means your code is executing faster than expected — possibly from a runaway loop or skipped logic — which WWDG treats as an error too.

WWDG window and kick zones
WWDG Window concept:
Counter: T[6:0] counts DOWN from T to 0x40 (reset threshold)
T (initial)W (window)0x3F (reset boundary)
forbidden zone
Kick here = TOO EARLY → RESET
allowed kick zone
Kick here = VALID
Reset fires
if no kick
Timeline:
T
forbidden
W
valid kick zone
0x40
RESET
T = WWDG_CR[6:0] (initial counter, e.g. 0x7F = 127)
W = WWDG_CFR[6:0] (window, e.g. 0x5F = 95)
Allowed kick when: 0x40 ≤ counter ≤ W

WWDG Registers

OffsetRegisterBitsDescription
0x00WWDG_CR[6:0] T — counter valueLoad counter with T[6:0]. Write T with bit 6 set (e.g., 0x7F). Set WDGA=1 to start (bit 7). Cannot be cleared once set.
0x00WWDG_CR[7] WDGAActivation bit: write 1 to start WWDG. Cannot clear after setting.
0x04WWDG_CFR[6:0] W — window valueCounter must be ≤ W when refreshed. If refreshed when counter > W → reset.
0x04WWDG_CFR[8:7] WDGTBTimer base: 00=÷1 (fastest), 01=÷2, 10=÷4, 11=÷8 (slowest)
0x04WWDG_CFR[9] EWIEarly wakeup interrupt: fires when counter = 0x40 (just before reset). Use to log fault info.
0x08WWDG_SR[0] EWIFEarly wakeup interrupt flag. Clear by writing 0.

WWDG Timing Formula

WWDG runs on PCLK1 (42 MHz) divided by 4096 internally, then by WDGTB:

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

The window T[5:0] = (counter[6:0] AND 0x3F), counter starts at T, resets when it reaches 0x3F (64).

WDGTBDivisorMin (T[5:0]=0)Max (T[5:0]=63)
00÷1~97.5 µs~6.24 ms
01÷2~195 µs~12.5 ms
10÷4~390 µs~24.9 ms
11÷8~780 µs~49.9 ms

WWDG Bare-Metal Code

C — WWDG with early wakeup interrupt

#include <stdint.h>

#define WWDG_BASE  0x40002C00UL
#define WWDG_CR    (*(volatile uint32_t *)(WWDG_BASE+0x00))
#define WWDG_CFR   (*(volatile uint32_t *)(WWDG_BASE+0x04))
#define WWDG_SR    (*(volatile uint32_t *)(WWDG_BASE+0x08))
#define RCC_APB1ENR (*(volatile uint32_t *)0x40023840)

/* WWDG config:
   PCLK1 = 42 MHz, WDGTB = 11 (÷8), T = 0x7F, W = 0x5F
   Max period (from T=0x7F) = 4096×8×64/42MHz ≈ 49.9ms
   Window opens when counter ≤ 0x5F (after ~12.3ms)
   Kick allowed: 12.3ms to 49.9ms after last kick
   → detect hang (>49.9ms) AND runaway (<12.3ms) */

void WWDG_Init(void) {
    /* Enable WWDG clock */
    RCC_APB1ENR |= (1<<11);  /* WWDGEN bit 11 */

    /* Configure CFR: WDGTB=11 (÷8), W=0x5F, EWI=1 */
    WWDG_CFR = (0x5F) |     /* W = 0x5F (window upper bound) */
               (3<<7) |     /* WDGTB = 11 = ÷8 */
               (1<<9);     /* EWI = 1 (early interrupt before reset) */

    /* CR: load counter T=0x7F, start WDGA */
    WWDG_CR = 0x7F |        /* T[6:0] = 0x7F (127) */
              (1<<7);      /* WDGA = 1 (start) */

    /* Enable WWDG EWI IRQ (IRQ0) in NVIC */
    volatile uint32_t *NVIC_ISER0 = (volatile uint32_t *)0xE000E100;
    *NVIC_ISER0 |= (1<<0);
}

/* Kick WWDG — MUST be called within the allowed window (W > counter > 0x3F) */
void WWDG_Kick(void) {
    /* Reload CR with T=0x7F (restart from 127) */
    WWDG_CR = (0x7F) | (1<<7);  /* WDGA must stay 1 */
    /* Counter: 0x7F (127) → counts down → 0x40 (64) → RESET
       Write this only when counter ≤ W (0x5F) */
}

/* EWI fires when counter = 0x40 — one last chance before reset.
   Use to: log fault, save state, signal error LED */
void WWDG_IRQHandler(void) {
    /* Clear EWI flag (write 0 to EWIF) */
    WWDG_SR = 0;
    /* System will reset in ~780µs unless we kick here */
    /* Log error, flash LED, etc. — do NOT kick normally here */
}

void main_loop_task(void) {
    /* This task takes 15–40ms — safely within the 12.3–49.9ms window */
    do_work();
    WWDG_Kick();  /* kick in allowed window */
}
Never kick WWDG before the window opens. Kicking when counter > W (before the window opens) causes an immediate reset — just like a timeout. The WWDG window must overlap with your normal execution timing.

04 Detecting Reset Source

After reset, check RCC_CSR flags to determine why the reset occurred. Always clear them after reading to avoid false triggers on next boot.

C — Read and clear reset cause flags

#define RCC_CSR  (*(volatile uint32_t *)0x40023874)

void check_reset_cause(void) {
    uint32_t csr = RCC_CSR;

    if (csr & (1<<29)) /* WWDGRSTF */
        log("WWDG watchdog reset\r\n");
    if (csr & (1<<28)) /* IWDGRSTF */
        log("IWDG watchdog reset\r\n");
    if (csr & (1<<27)) /* SFTRSTF */
        log("Software reset (AIRCR)\r\n");
    if (csr & (1<<26)) /* PORRSTF */
        log("Power-on reset\r\n");
    if (csr & (1<<25)) /* PINRSTF */
        log("NRST pin reset\r\n");
    if (csr & (1<<24)) /* BORRSTF */
        log("Brown-out reset\r\n");
    if (csr & (1<<31)) /* LPWRRSTF */
        log("Low-power reset\r\n");

    /* Clear all reset flags */
    RCC_CSR |= (1<<24);  /* RMVF = 1 → clears all RSTF flags */
}

05 Watchdog Usage Patterns

Pattern 1: Simple main-loop kick

Kick at the end of each main loop iteration. Simple but only detects complete hangs — if the loop is running but a task is stuck, IWDG won’t help unless that task is the last thing before the kick.

Pattern 2: Task checkpoint bitmap

Each task sets a bit in a bitmap when it completes its cycle. The watchdog kick only happens when all task bits are set. If any task hangs, the bitmap never completes, the kick never happens, and IWDG resets the chip.

C — Multi-task checkpoint pattern

#define TASK_A  (1<<0)
#define TASK_B  (1<<1)
#define TASK_C  (1<<2)
#define ALL_TASKS (TASK_A|TASK_B|TASK_C)

volatile uint32_t wdg_tasks_done = 0;

void task_done(uint32_t task_flag) {
    wdg_tasks_done |= task_flag;
    if (wdg_tasks_done == ALL_TASKS) {
        IWDG_Kick();
        wdg_tasks_done = 0;
    }
}

void task_A(void) { /* ... work ... */ task_done(TASK_A); }
void task_B(void) { /* ... work ... */ task_done(TASK_B); }
void task_C(void) { /* ... work ... */ task_done(TASK_C); }
Pattern 3: Debug freeze (disable in debugger)

When debugging with a JTAG/SWD probe and halting at a breakpoint, the watchdog keeps running and resets the chip. Configure DBG registers to freeze the watchdog when the core is halted:

C — Freeze IWDG+WWDG during debug halt

#define DBG_APB1_FZ  (*(volatile uint32_t *)0xE0042008)
/* Set these bits before starting watchdog (only effective with JTAG/SWD connected) */
DBG_APB1_FZ |= (1<<11);  /* DBG_WWDG_STOP */
DBG_APB1_FZ |= (1<<12);  /* DBG_IWDG_STOP */

06 Tips & Common Mistakes

Pitfalls
  • Kicking WWDG outside the window: If you refresh WWDG when counter > W (too early), you get an immediate reset. Calculate window timing carefully and verify with logic analyzer or oscilloscope.
  • IWDG in Stop/Standby: IWDG keeps running on LSI in Stop and Standby modes. If your wake period exceeds the IWDG timeout, the chip resets while asleep. Extend the timeout or disable (cannot disable once started — plan before enabling).
  • LSI frequency variance: LSI is typically 32 kHz but can range 17–47 kHz across temperature and voltage. For safety-critical timeout accuracy, calibrate LSI against an accurate reference (RTC, HSE).
  • Forgot to unlock PR/RLR: Writing to IWDG_PR/RLR without first writing 0x5555 to IWDG_KR is silently ignored. Always unlock first.
  • WWDG clock dependency: WWDG stops when PCLK1 stops (in Stop mode). Use IWDG for all deep-sleep fault detection.

STM32F407 Tutorial Series — Tutorial 22: Watchdog Timers  | ← Low Power | Board Overview →

Bare-metal register-level programming  ·  No HAL library  ·  STM32F407VGT6  ·  All 22 tutorials complete.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

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