Start the STM32 IWDG at boot with the IWDG_SW option bit cleared
Make the STM32L4 independent watchdog start by itself at reset by clearing the IWDG_SW option bit, so a boot hang cannot go unnoticed.
By default the independent watchdog of an STM32 is a software watchdog: it does nothing until your code starts it. A program that hangs before it reaches the start call is not protected at all. The option bit IWDG_SW fixes that. With the bit cleared, the watchdog is hardware-started and runs from the moment of reset, with no way to stop it. This is the STM32L4 option byte, written with the STM32CubeL4 HAL.
#include <stdio.h>
void make_iwdg_hardware(void)
{
FLASH_OBProgramInitTypeDef ob = {0};
HAL_FLASH_Unlock();
HAL_FLASH_OB_Unlock();
ob.OptionType = OPTIONBYTE_USER;
ob.USERType = OB_USER_IWDG_SW;
ob.USERConfig = OB_IWDG_HW; /* IWDG_SW = 0: started by hardware */
HAL_FLASHEx_OBProgram(&ob);
printf("IWDG_SW cleared, reloading\n");
HAL_FLASH_OB_Launch(); /* resets the chip to load the option bytes */
}IWDG_SW cleared, reloadingThe new value takes effect after HAL_FLASH_OB_Launch, which resets the device. From then on every reset starts the watchdog with its default reload of 4095 at the slowest prescaler, so the startup code has to refresh it, or at least configure it, within that first period, which is about 4 s on the nominal 32 kHz clock. Option bytes are non-volatile, so this is a one-time step in the manufacturing flow and not in each boot. The bit is described in the FLASH chapter of the STM32L4 reference manual RM0351.
Changing it back needs a mass erase or a debugger with option-byte access, so a hardware watchdog is hard to recover with a bad image.