STM8L 的独立看门狗由内部专门的 38Khz 低速时钟驱动,即使主时钟发生故障,它也仍然有效。这里需要注意独立看门狗的时钟并不是准确的 38Khz,只是我们在估算的时候,以 38Khz 的频率来计算,看门狗对时间的要求不是很精确,所以,时钟有些偏差,都是可以接受的。根据分频系统和看门狗计数值可以设置独立看门狗的复位时间,范围从0.1ms~1724.63ms
例程展示如何重载IWDG计数值,IWDG的时间设置为214.7ms。程序采用“Refresh”变量来使能IWDG重载计数值仿真IWDG复位,并且板上LED4翻转。当按键按下,模拟一次软件错误造成程序没有喂狗,从而发生复位。如果IWDG复位,系统启动后LED3会翻转8次,主代码如下:
void main(void)
{
uint8_t Index;
GPIO_Init(LED3_PORT,LED3_PIN,GPIO_Mode_Out_PP_Low_Fast);
//输出低电平-高速10M
GPIO_Init(LED4_PORT,LED4_PIN,GPIO_Mode_Out_PP_Low_Fast);
//输出低电平-高速10M
GPIO_Init(KEY_PORT,KEY_PIN,GPIO_Mode_In_FL_IT);
//输入浮空-中断
/* Set PC1 sensitivity to falling edge and low level 下降沿低电平触发*/
EXTI_SetPinSensitivity(EXTI_Pin_1, EXTI_Trigger_Falling_Low);
/* Check if the MCU has resumed from IWDG reset */
if (RST_GetFlagStatus(RST_FLAG_IWDGF) != RESET)
{
/* IWDGF flag set */
/* Toggle LED3 */
for (Index = 7; Index != 0; Index--)
{
GPIO_ToggleBits(LED3_PORT,LED3_PIN);
Delay(0x7FFF);
}
/* Clear IWDGF Flag */
RST_ClearFlag(RST_FLAG_IWDGF);
}
/* IWDG configuration: IWDG is clocked by LSI = 38KHz */
/* IWDG timeout equal to 214.7 ms (the timeout may varies due to LSI frequency dispersion) */
/* IWDG timeout = (RELOAD_VALUE + 1) * Prescaler / LSI = (254 + 1) * 32 / 38 000 = 214.7 ms */
/* Enable the IWDG */
IWDG_Enable();
/* Enable write access to IWDG_PR and IWDG_RLR registers */
IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
/* Set IWDG timeout */
IWDG_SetPrescaler(IWDG_Prescaler_32);
IWDG_SetReload(RELOAD_VALUE);
/* Refresh IWDG */
IWDG_ReloadCounter();
/* enable interrupts by switching to level 0 */
enableInterrupts();
while (1)
{
/* As Refresh is equal to ENABLE no IWDG reset will occur. When Refresh is
equal to DISABLE, the IWDG counter isn't refreshed and IWDG reset will occur. */
if (Refresh != 0)
{
/* Reload IWDG counter */
IWDG_ReloadCounter();
}
/* Toggle LED4 */
GPIO_ToggleBits(LED4_PORT,LED4_PIN);
Delay(0x6FFF);
}
}