DEV Community

Hedy
Hedy

Posted on

How does STM32 initialize the watchdog and feed dog?

On an STM32 microcontroller, initializing and refreshing ("feeding") the watchdog(What is a Watchdog?) timer ensures that your system can recover from software faults. STM32 typically supports two types of watchdogs:

Image description

1. Independent Watchdog (IWDG)
Characteristics

  • Runs from its own low-speed clock (LSI ~32 kHz).
  • Independent of main system clock.
  • Once started, cannot be stopped unless you reset the MCU.
  • Used for critical fault recovery.

Initialization (using HAL)

c

#include "stm32f4xx_hal.h"

IWDG_HandleTypeDef hiwdg;

void IWDG_Init(void) {
    hiwdg.Instance = IWDG;
    hiwdg.Init.Prescaler = IWDG_PRESCALER_64;       // Choose prescaler
    hiwdg.Init.Reload = 1000;                        // Set reload value (max 0xFFF)
    if (HAL_IWDG_Init(&hiwdg) != HAL_OK) {
        // Handle error
    }
}
Enter fullscreen mode Exit fullscreen mode

"Feeding the dog" (refresh)

c

HAL_IWDG_Refresh(&hiwdg);
Enter fullscreen mode Exit fullscreen mode

Call HAL_IWDG_Refresh() periodically before the counter expires, or the MCU will reset.

IWDG Timeout Formula

ini

Timeout = (Reload + 1) * Prescaler / LSI_Frequency
Enter fullscreen mode Exit fullscreen mode

Example: Reload = 1000, Prescaler = 64, LSI ≈ 32,000 Hz
→ Timeout ≈ (1001 × 64) / 32000 ≈ 2 seconds

2. Window Watchdog (WWDG)
Characteristics

  • Runs on APB clock.
  • More flexible: allows windowed feeding (must refresh within a specific time frame).
  • Can trigger early warnings via interrupt.

Initialization (HAL)

c

#include "stm32f4xx_hal.h"

WWDG_HandleTypeDef hwwdg;

void WWDG_Init(void) {
    hwwdg.Instance = WWDG;
    hwwdg.Init.Prescaler = WWDG_PRESCALER_8;
    hwwdg.Init.Window    = 80;         // Refresh window
    hwwdg.Init.Counter   = 127;        // Initial counter
    hwwdg.Init.EWIMode   = WWDG_EWI_DISABLE;
    if (HAL_WWDG_Init(&hwwdg) != HAL_OK) {
        // Handle error
    }
}
Enter fullscreen mode Exit fullscreen mode

Refresh WWDG

c

HAL_WWDG_Refresh(&hwwdg);
Enter fullscreen mode Exit fullscreen mode

Must refresh before counter hits 63 but after it drops below Window.

Summary: IWDG vs WWDG

Image description

Tips for Use

  • Enable LSI for IWDG (done automatically via HAL).
  • Call refresh() in your main loop or task scheduler.
  • If using an RTOS, feed the watchdog from a low-priority task that runs last.
  • Avoid feeding in ISRs unless absolutely necessary.

Top comments (0)