watchdog-iwdg.c

STM32 Nucleo-64 F4 family — flagship: Nucleo-F401RE · File : watchdog-iwdg.c · Language : C · Use case : Surveiller le programme avec le watchdog IWDG et redémarrer en cas de blocage

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 F4 board (STM32F401RE/F411RE, Cortex-M4) 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

Create a STM32CubeIDE project (pick Nucleo-F401RE or F411RE), paste the code into main.c, configure peripherals in the .ioc, then Run. The ST-LINK serial terminal 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();
    }
  }
}

← Back to the board