● Significance of the Watchdog
1、 The c language execution process
In microcontrollers, c programs execute sequentially starting from address 0, where the PC pointer indicates the current execution address. For the STM32F407, as the code executes, the PC pointer continuously moves along the memory addresses. When it reaches the last statement of the main function, unless there are special circumstances, the PC pointer will continue to move until it reaches address 4GB-1Z, ultimately the PC pointer loops back to address 0. Therefore, you will often see that the last statement of many main functions is a while infinite loop!!! The PC pointer will remain at your infinite loop position, preventing the code from starting over and thus avoiding a reset!
2、 The watchdog
A watchdog is something that barks incessantly in special circumstances to generate an alarm. In microcontrollers, the watchdog functions similarly, but this dog only alarms when it is ‘hungry’ (the alarm here usually means a reset). The watchdog is essentially a countdown timer; if it counts down to 0, it will trigger a reset! When we initialize the watchdog, we can give it an initial count value, and once the watchdog is enabled, it starts counting down. When it will count to zero depends on your initialization. For example, if we configure a watchdog for 3s to count down to zero, you must ‘feed’ it (reset its count value) within less than 3s to prevent it from resetting.
Therefore, we can understand that the watchdog’s working principle is to initialize a technical value and feed the watchdog before it reaches zero. Since the watchdog is always working, you must continuously feed it (like a pet dog that needs three meals a day; if you miss one meal, it starts to act cute^_^).
Assuming we configure the watchdog to count down to zero in 3s, and we create an infinite loop that feeds it every 2s, then this dog will not go hungry. However, the microcontroller might experience a runaway program, meaning the code does not follow your intended path, and thus your feeding program cannot execute. At this point, if 3s passes, the dog will become hungry and trigger a reset. This illustrates the function of the watchdog: as long as you configure it correctly and feed it on time, it will only reset when the program runs away. Generally, large projects will use a watchdog; if the machine itself has a problem, it can reset immediately without causing a freeze.
● From Manual to Process
1、 STM32 Watchdog
1) Function Description
2) Registers
2、 Initialization Process
1) Open the timer clock from RCC.
2) Write 0X5555 to the key register to unlock protection
3) Set the prescaler value
4) Set the reload count value
5) Write 0xcccc to the key register to enable the watchdog
● From Process to Code
1) Initialization
2) Feed the Dog