stm32 的RTC是一个32位的计数器,他能在电源断电的情况下利用,锂电池继续工作供电。具有秒中断。
使用RTC主要是3个操作:
1、初始化。
2、写RTCCounter的值。
3、读RTCCoutner的值。
然后就是软件的工作了,可以利用unix时间戳处理时间,time.h中有对应的处理函数,lacoaltime等。
1#include "rtc.h" 2 3//void NVIC_Configuration(void) 4//{ 5// NVIC_InitTypeDef NVIC_InitStructure; 6// 7// /* Configure one bit for preemption priority */ 8// NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); 9// 10// /* Enable the RTC Interrupt */ 11// NVIC_InitStructure.NVIC_IRQChannel = RTC_IRQn; 12// NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; 13// NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; 14// NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; 15// NVIC_Init(&NVIC_InitStructure); 16//} 17void RTC_Configuration(void) 18{ 19 /* Enable PWR and BKP clocks */ 20 RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE); 21 22 /* Allow access to BKP Domain */ 23 PWR_BackupAccessCmd(ENABLE); 24 25 /* Reset Backup Domain */ 26 BKP_DeInit(); 27 28 /* Enable LSE */ 29 RCC_LSEConfig(RCC_LSE_ON); 30 /* Wait till LSE is ready */ 31 while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET) 32 {} 33 34 /* Select LSE as RTC Clock Source */ 35 RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE); 36 37 /* Enable RTC Clock */ 38 RCC_RTCCLKCmd(ENABLE); 39 40 /* Wait for RTC registers synchronization */ 41 RTC_WaitForSynchro(); 42 43 /* Wait until last write operation on RTC registers has finished */ 44 RTC_WaitForLastTask(); 45 46 /* Enable the RTC Second */ 47 //RTC_ITConfig(RTC_IT_SEC, ENABLE); 48 49 /* Wait until last write operation on RTC registers has finished */ 50 RTC_WaitForLastTask(); 51 52 /* Set RTC prescaler: set RTC period to 1sec */ 53 RTC_SetPrescaler(32767); /* RTC period = RTCCLK/RTC_PR = (32.768 KHz)/(32767+1) */ 54 55 /* Wait until last write operation on RTC registers has finished */ 56 RTC_WaitForLastTask(); 57} 58void Set_RTC_Cnt(uint32_t counter) 59{ 60 /* Wait until last write operation on RTC registers has finished */ 61 RTC_WaitForLastTask(); 62 /* Change the current time */ 63 RTC_SetCounter(counter); 64 RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE); 65 PWR_BackupAccessCmd(ENABLE); //必须开启,不然无法写入 66 /* Wait until last write operation on RTC registers has finished */ 67 RTC_WaitForLastTask(); 68} 69 70struct tm* Get_Now_Time(void) //unix时间戳相关处理,可以看一下time.h 71{ 72 uint32_t temp = RTC_GetCounter(); 73 struct tm * t = localtime(&temp); 74 t->tm_year+=1900; 75 t->tm_mon +=1; 76 return t; 77}
秒中断想使用的话可以开一下不用的话,不用开。
值的注意的一点事,当写RTCCounter寄存器时,必须开启备份寄存器相关,
RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
PWR_BackupAccessCmd(ENABLE);
如果不加入这两句话程序会死在RTC_WaitForLastTask();这个地方,因为写寄存器无法完成所以会一直等待其完成。
具体可以看一下这个帖子: