RTC_WakeUp唤醒STM32F4停止模式(借鉴的是原子哥写的代码):
首先我们先初始化RTC配置:
//RTC初始化
u8 MyRTC_Init(void)
{
RTC_InitTypeDef RTC_InitStructrue;
u16 retry=0x1FFF;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR,ENABLE);//使能PWR时钟
PWR_BackupAccessCmd(ENABLE);//使能后备寄存器
if(RTC_ReadBackupRegister(RTC_BKP_DR0)!=0x5050)
{
RCC_LSEConfig(RCC_LSE_ON);//开启低速外部时钟
if(RCC_GetFlagStatus(RCC_FLAG_LSERDY)==RESET)//读取外部低速时钟是否准备就绪
{
retry++;
delay_ms(10);
}
if(retry==0)
return 1;//LSE开启失败
RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);//选择LSE作为RTC时钟
RCC_RTCCLKCmd(ENABLE);//使能RTC时钟
RTC_InitStructrue.RTC_AsynchPrediv=0x7F;//RTC异步分频系数127
RTC_InitStructrue.RTC_SynchPrediv=0xFF;//RTC同步分频系数255
RTC_Init(&RTC_InitStructrue);//RTC初始化函数
RTC_WriteBackupRegister(RTC_BKP_DR0,0x5050);
}
return 0;
}
然后配置RTC_WakeUp:
void RTC_Set_WakeUp(u16 waketime)
{
EXTI_InitTypeDef EXTI_InitStruct;
NVIC_InitTypeDef NVIC_InitStruct;
RTC_WakeUpCmd(DISABLE);//关闭Wake Up
RTC_WakeUpClockConfig(RTC_WakeUpClock_CK_SPRE_16bits);//时钟选择1Hz
RTC_SetWakeUpCounter(waketime);//设置WakeUp自动重装载值
RTC_ClearITPendingBit(RTC_IT_WUT);//清除WakeUp中断标志
EXTI_ClearITPendingBit(EXTI_Line22);//清除Line22中断标志
RTC_ITConfig(RTC_IT_WUT,ENABLE);//开启WakeUp中断标志
RTC_WakeUpCmd(ENABLE);//开启WakeUp
EXTI_InitStruct.EXTI_Line=EXTI_Line22;//LINE22
EXTI_InitStruct.EXTI_LineCmd=ENABLE;
EXTI_InitStruct.EXTI_Mode=EXTI_Mode_Interrupt;
EXTI_InitStruct.EXTI_Trigger=EXTI_Trigger_Rising;//上升沿触发
EXTI_Init(&EXTI_InitStruct);
NVIC_InitStruct.NVIC_IRQChannel=RTC_WKUP_IRQn;//选择WakeUp中断
NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=0x01;
NVIC_InitStruct.NVIC_IRQChannelSubPriority=0x02;
NVIC_Init(&NVIC_InitStruct);
}
编写RTC_WakeUp中断函数(记得初始化系统时钟):
void RTC_WKUP_IRQHandler()
{
while(RTC_GetFlagStatus(RTC_FLAG_WUTF)!=RESET)
{
RTC_ClearFlag(RTC_FLAG_WUTF);
SystemInit();
LED1=!LED1;
}
EXTI_ClearITPendingBit(EXTI_Line22);
}
然后就是main函数了:
int main(void)
{
u8 t=0;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//设置系统中断优先级分组2
delay_init(168); //初始化延时函数
uart_init(9600); //初始化串口波特率为9600
LED_Init(); //初始化LED
KEY_Init();
MyRTC_Init();
while(1)
{
LED0=!LED0;
RTC_Set_WakeUp(5);//时钟频率选的1Hz,5S产生一次RTC_WakeUp中断
printf("t=%d\n\r",t);
PWR_EnterSTOPMode(PWR_LowPowerRegulator_ON,PWR_STOPEntry_WFI);
t++;
if(t>30)
t=0;
}
把USART1接串口调试助手上,变量t从0开始每5秒加1,同时LED每5秒反转一次状态.
**注意哈:
停止模式是烧录不进程序的,要烧录程序的话,要先按住RESET键,点download后,松手就能下进去了.**