stm32 的RTC是一个32位的计数器,他能在电源断电的状况下利用,锂电池继续工做供电。具备秒中断。html
使用RTC主要是3个操做:
函数
一、初始化。
ui
二、写RTCCounter的值。unix
三、读RTCCoutner的值。
code
而后就是软件的工做了,能够利用unix时间戳处理时间,time.h中有对应的处理函数,lacoaltime等。htm
#include "rtc.h" //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); //} void RTC_Configuration(void) { /* Enable PWR and BKP clocks */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE); /* Allow access to BKP Domain */ PWR_BackupAccessCmd(ENABLE); /* Reset Backup Domain */ BKP_DeInit(); /* Enable LSE */ RCC_LSEConfig(RCC_LSE_ON); /* Wait till LSE is ready */ while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET) {} /* Select LSE as RTC Clock Source */ RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE); /* Enable RTC Clock */ RCC_RTCCLKCmd(ENABLE); /* Wait for RTC registers synchronization */ RTC_WaitForSynchro(); /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); /* Enable the RTC Second */ //RTC_ITConfig(RTC_IT_SEC, ENABLE); /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); /* Set RTC prescaler: set RTC period to 1sec */ RTC_SetPrescaler(32767); /* RTC period = RTCCLK/RTC_PR = (32.768 KHz)/(32767+1) */ /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); } void Set_RTC_Cnt(uint32_t counter) { /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); /* Change the current time */ RTC_SetCounter(counter); RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE); PWR_BackupAccessCmd(ENABLE); //必须开启,否则没法写入 /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); } struct tm* Get_Now_Time(void) //unix时间戳相关处理,能够看一下time.h { uint32_t temp = RTC_GetCounter(); struct tm * t = localtime(&temp); t->tm_year+=1900; t->tm_mon +=1; return t; }
秒中断想使用的话能够开一下不用的话,不用开。ip
值的注意的一点事,当写RTCCounter寄存器时,必须开启备份寄存器相关,it
RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);io
PWR_BackupAccessCmd(ENABLE); ast
若是不加入这两句话程序会死在RTC_WaitForLastTask();这个地方,由于写寄存器没法完成因此会一直等待其完成。
具体能够看一下这个帖子:
http://bbs.21ic.com/icview-774636-1-1.html