①wwdg.h:
#ifndef wwdg_h
#define wwdg_h
#include “sys.h”
void iwdg_init(u8 prer,u16 rlr);
void iwdg_feed(void);
void wwdg_init(u8 tr,u8 wr, u32 fprer);//初始化wwdg
void wwdg_setcounter(u8 cnt); //设置wwdg的计数器
void wwdg_nvic_init(void);
#endif
②wwdg.c:
#include “wwdg.h”
#include “led.h”
void IWDG_Init(u8 prer,u16 rlr)
{
IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable); //使能对寄存器IWDG_PR和IWDG_RLR的写操作
IWDG_SetPrescaler(prer); //设置IWDG预分频值:设置IWDG预分频值为64
IWDG_SetReload(rlr); //设置IWDG重装载值
IWDG_ReloadCounter(); //按照IWDG重装载寄存器的值重装载IWDG计数器
IWDG_Enable(); //使能IWDG
}
//喂独立看门狗
void IWDG_Feed(void)
{
IWDG_ReloadCounter(); //重载计数值
}
//保存WWDG计数器的设置值,默认为最大.
u8 WWDG_CNT=0x7f;
//初始化窗口看门狗
//tr :T[6:0],计数器值
//wr :W[6:0],窗口值
//fprer:分频系数(WDGTB),仅最低2位有效
//Fwwdg=PCLK1/(4096*2^fprer).
void WWDG_NVIC_Init()
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = WWDG_IRQn; //WWDG中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; //抢占2,子优先级3,组2
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //抢占2,子优先级3,组2
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);//NVIC初始化
}
void WWDG_Init(u8 tr,u8 wr,u32 fprer)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_WWDG, ENABLE); // WWDG时钟使能
WWDG_CNT=tr&WWDG_CNT; //初始化WWDG_CNT.
WWDG_SetPrescaler(fprer);设置IWDG预分频值
WWDG_SetWindowValue(wr);//设置窗口值
WWDG_Enable(WWDG_CNT); //使能看门狗 , 设置 counter .
WWDG_ClearFlag();//清除提前唤醒中断标志位
WWDG_NVIC_Init();//初始化窗口看门狗 NVIC
WWDG_EnableIT(); //开启窗口看门狗中断
}
//重设置WWDG计数器的值
void WWDG_Set_Counter(u8 cnt)
{
WWDG_Enable(cnt);//使能看门狗 , 设置 counter .
}
//窗口看门狗中断服务程序
void WWDG_IRQHandler(void)
{
//WWDG_SetCounter(WWDG_CNT); //当禁掉此句后,窗口看门狗将产生复位
WWDG_ClearFlag(); //清除提前唤醒中断标志位
LED1=!LED1; //LED状态翻转
}
③main:
#include “led.h”
#include “delay.h”
#include “key.h”
#include “sys.h”
#include “usart.h”
#include “wwdg.h”
int main(void)
{
delay_init(); //延时函数初始化
uart_init(115200);
LED_Init(); //LED端口初始化
KEY_Init(); //按键初始化
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
//设置中断优先级分组为组2:2位抢占优先级,2位响应优先级
LED0=0;
delay_ms(200);
wwdg_init(0X7F,0X5F,WWDG_Prescaler_8);
//计数器值为7f,窗口寄存器为5f,分频数为8
while(1)
{
LED0=1;
}
}