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