How to implement fail-safes and watchdog timers on STM32 microcontrollers?


Let’s cover how to implement fail-safes and watchdog timers on STM32 microcontrollers, specifically with STM32CubeMX and HAL library (common tools for STM32 development).
Overview
Independent Watchdog Timer (IWDG): Runs on an internal 32 kHz LSI clock; works even if the main clock fails.
Window Watchdog Timer (WWDG): Tighter control; must be refreshed within a specific time window.
Fail-safes: Custom logic to handle faults like sensor timeout, peripheral failure, or invalid data.
Part 1: Enable the Independent Watchdog (IWDG) in STM32CubeMX
Steps in STM32CubeMX:
Open your project in CubeMX.
Go to "Peripherals" > "IWDG", and enable it.
Set Prescaler and Reload Counter to control the timeout period.
Enable "Start at Reset" if you want it active from boot.
Generate code and open in your IDE (e.g., STM32CubeIDE).
Part 2: Use HAL Code to Control the Watchdog
In main.c
:
Initialization (if not auto-started):
c
HAL_IWDG_Start(&hiwdg);
Refresh Watchdog in your main loop:
c
while (1)
{
HAL_IWDG_Refresh(&hiwdg); // Kick the watchdog
// Your logic here
}
If
HAL_IWDG_Refresh()
is not called before timeout, the MCU resets.
Part 3: Implementing a Custom Fail-safe
Let’s say your system uses a sensor. If the sensor fails to respond within 2 seconds, go into a fail-safe mode:
c
uint32_t lastSensorTime = 0;
const uint32_t sensorTimeout = 2000; // milliseconds
while (1)
{
HAL_IWDG_Refresh(&hiwdg); // Keep MCU alive
if (Sensor_ReadOK())
{
lastSensorTime = HAL_GetTick();
}
if ((HAL_GetTick() - lastSensorTime) > sensorTimeout)
{
FailSafe_StopAll(); // Disable motors, signal error
}
HAL_Delay(10); // Keep loop timing stable
}
Fail-safe Actions Might Include:
Turning off actuators
Blinking an LED
Entering low-power mode
Logging an error to flash or EEPROM
Triggering a soft reset (
NVIC_SystemReset()
)
Bonus: Enable Watchdog Reset Detection
If you want to detect if a reset was caused by IWDG, check the reset flags:
c
if (__HAL_RCC_GET_FLAG(RCC_FLAG_IWDGRST))
{
// Watchdog reset occurred
__HAL_RCC_CLEAR_RESET_FLAGS(); // Clear flags
}
Tools and Libraries
STM32CubeMX (watchdog setup)
STM32 HAL (IWDG, WWDG)
FreeRTOS (has WDT hooks if you use an RTOS)
STM32CubeMonitor (runtime monitoring)
Subscribe to my newsletter
Read articles from ampheo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
