watchdog-iwdg.c
The independent watchdog IWDG resets the board when the firmware stops refreshing it: here a simulated infinite loop triggers the reset after 30 cycles. The serial port clearly shows the automatic reboot.
Hardware
A Nucleo H7 board (STM32H743ZI, Cortex-M7 @ 480 MHz) programmed via ST-LINK (USB), 3.3 V pins. USB cable + serial terminal to watch the successive boots.
Wiring
No wiring. In CubeMX enable IWDG (LSI clock, prescaler and reload for a ~2 s timeout).
How it works
Once started, the IWDG cannot be stopped: if HAL_IWDG_Refresh is not called before the reload expires, the chip hard-resets. The boot printf proves the reboot happened.
Running it
STM32CubeIDE project based on the Nucleo-H743ZI: drop the code into main.c, declare peripherals in the .ioc, then Run over ST-LINK. The ST-LINK serial monitor shows printf at 115200.
Variants
Save a reboot counter in a RTC backup register or flash to trace crashes, or refresh the dog inside a dedicated RTOS task.
watchdog-iwdg.c
// IWDG : si le firmware ne « rafraichit » plus le chien, reset.
#include "main.h"
extern IWDG_HandleTypeDef hiwdg; // LSI/64, reload ~2 s dans CubeMX
extern UART_HandleTypeDef huart2;
int __io_putchar(int ch) {
HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
return ch;
}
static void tache_critique(void) {
// Simule un blocage au bout de 30 appuis (test du watchdog).
static int n = 0;
if (++n == 30) for (;;);
}
int main(void) {
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_IWDG_Init(); // demarre le chien des la configuration
printf("Boot. Rafraichissement IWDG toutes les 500 ms\r\n");
uint32_t t0 = 0;
for (;;) {
if (HAL_GetTick() - t0 >= 500) {
t0 = HAL_GetTick();
HAL_IWDG_Refresh(&hiwdg); // « je suis vivant »
printf("OK\r\n");
tache_critique();
}
}
}