stm32 RTC

    stm32 的RTC是一个32位的计数器,他能在电源断电的情况下利用,锂电池继续工作供电。具有秒中断。

    使用RTC主要是3个操作:

    1、初始化。

    2、写RTCCounter的值。

    3、读RTCCoutner的值。

    然后就是软件的工作了,可以利用unix时间戳处理时间,time.h中有对应的处理函数,lacoaltime等。

#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;
}

秒中断想使用的话可以开一下不用的话,不用开。

值的注意的一点事,当写RTCCounter寄存器时,必须开启备份寄存器相关,

RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);

PWR_BackupAccessCmd(ENABLE); 

如果不加入这两句话程序会死在RTC_WaitForLastTask();这个地方,因为写寄存器无法完成所以会一直等待其完成。

具体可以看一下这个帖子:

http://bbs.21ic.com/icview-774636-1-1.html

评论

暂无评论