RTC简介

实时时钟是一个独立的定时器。RTC模块拥有一组连续计数的计数器,在相应软件配置下,可提供时钟日历的功能。修改计数器的值可以重新设置系统当前的时间和日期。

注意事项

-1- 要手动配置中断寄存器

-2- 需要等待写操作完成

-3- 时钟闹钟中段在同一个中断函数中

配置时钟

调用函数RTC_SetCounter();

函数里面的参数可通过计算获得如下图

配置闹钟

调用函数RTC_SetAlarm();

函数里面的参数和时钟相同

代码编写 (F1可直接拷贝使用)

#include "stm32f10x.h"#include "usart.h"uint32_t TimeDisplay;u32Set_RTCTIME(u8 Hour,u8 Minute,u8 Sec);void NVIC_Configuration(void){NVIC_InitTypeDef NVIC_InitStructure;/* Configure one bit for preemption priority */NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);/* Enable the RTC Interrupt */NVIC_InitStructure.NVIC_IRQChannel = RTC_IRQn;NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;NVIC_Init(&NVIC_InitStructure);RTC->CRH |= 0x02;} void RTC_Configuration(void) {//使能电源和后备接口时钟RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);//使能后备寄存器和RTC的访问 PWR_BackupAccessCmd(ENABLE);BKP_DeInit();RCC_LSEConfig(RCC_LSE_ON);while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET);RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);RCC_RTCCLKCmd(ENABLE);RTC_WaitForSynchro();RTC_WaitForLastTask();RTC_ITConfig(RTC_IT_SEC, ENABLE);RTC_WaitForLastTask();RTC_SetPrescaler(32767);RTC_WaitForLastTask(); }void Time_Adjust(void) {RTC_WaitForLastTask();RTC_SetCounter(Set_RTCTIME(16,24,50));RTC_WaitForLastTask();RTC_SetAlarm(Set_RTCTIME(16,24,53));RTC_WaitForLastTask(); } int main(void) {int a;NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);NVIC_Configuration();uart_init(115200);if (BKP_ReadBackupRegister(BKP_DR1) != 0xA5A5){printf("\r\n\n RTC not yet configured....");RTC_Configuration();printf("\r\n RTC configured....");Time_Adjust();BKP_WriteBackupRegister(BKP_DR1, 0xA5A5);}RCC_ClearFlag();while(1) {if( TimeDisplay==1 ){TimeDisplay=0;a=RTC_GetCounter();printf("%d\n", a / 3600);printf("%d\n",(a % 3600) / 60);printf("%d\n",(a % 3600) % 60);}} }void RTC_IRQHandler(void){if (RTC_GetITStatus(RTC_IT_SEC) != RESET){/* Clear the RTC Second interrupt */RTC_ClearITPendingBit(RTC_IT_SEC);TimeDisplay = 1;/* Wait until last write operation on RTC registers has finished */RTC_WaitForLastTask();}if (RTC_GetITStatus(RTC_IT_ALR) != RESET){/* Clear the RTC Second interrupt */RTC_ClearITPendingBit(RTC_IT_ALR);RTC_WaitForLastTask();printf("发生了闹钟的中断\r\n");}}u32Set_RTCTIME(u8 Hour,u8 Minute,u8 Sec){return((Hour*3600 + Minute*60 + Sec));} 

工程获取

三连加关注后点击头像获取