RTC程序
void RTC_Config(void)//配置实时时钟
{
u16 WaitForOscSource;
if(BKP_ReadBackupRegister(BKP_DR1)==CONFIGURATION_RESET)//从数据备份寄存器中取出数据
{
/*Enables the clock to Backup and power interface peripherals */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP | RCC_APB1Periph_PWR,ENABLE); //使能备份时钟和电源控制时钟
  WR_BackupAccessCmd(ENABLE); //使能对rtc和备份寄存器的访问
/* Backup Domain Reset */
BKP_DeInit(); //设置bkp外设到默认值
BKP_WriteBackupRegister(BKP_DR1, CONFIGURATION_DONE);//将CONFIGURATION_DONE写入BKP_DR1中
/*Enable 32.768 kHz external oscillator */
RCC_LSEConfig(RCC_LSE_ON); //配置外部低速晶振
// for(WaitForOscSource=0;WaitForOscSource<5000;WaitForOscSource++) ;//等待外部低速晶振开启
/* Wait till LSE is ready */
while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET)
{}
RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);//配置rtc时钟为外部低速时钟
/* RTC Enabled */
RCC_RTCCLKCmd(ENABLE); //使能rtc时钟
RTC_WaitForLastTask();
/*Wait for RTC registers synchronisation */
RTC_WaitForSynchro(); //等待rtc寄存器与apb同步
RTC_WaitForLastTask(); //等待rtc寄存器上最后一个写操作完成,在对rtc操作之前要先调用此函数
/* Setting RTC Interrupts-Seconds interrupt enabled */
/* 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 1 sec */
RTC_SetPrescaler(32767);//产生1s信号 /* RTC period = RTCCLK/RTC_PR = (32.768 KHz)/(32767+1) */
/* Prescaler is set to 32766 instead of 32768 to compensate for
lower as well as higher frequencies*/
/* Wait until last write operation on RTC registers has finished */
RTC_WaitForLastTask();
/* Set default system time to 00 : 0 : 00 */
//SetTime(DEFAULT_HOURS,DEFAULT_MINUTES,DEFAULT_SECONDS); //设置系统时间,设置rtc计数器
//此处不再设置计数初值,默认值从0开始,时间读取算法从2000年开始
// Set_Time(0,1,1,1,0,0);//时间初始值2000年1月1日1时0分0秒 3.12
// RTC_WaitForLastTask();
//时装调整 48/49对应每月快120s
BKP_SetRTCCalibrationValue(45); //设置rtc时钟校准值 3.12
///////////////////////////////////////////////////////
//校时公式
//ppm误差=每30天跑快的秒数/(30天*24小时*3600秒)*10的6次方
//校准值=(ppm误差/10^6)*2^20
////////////////////////////////////////////////////////
RTC_WaitForLastTask();
BKP_WriteBackupRegister(BKP_DR1, CONFIGURATION_DONE);
}
else
{
/* PWR and BKP clocks selection */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);
PWR_BackupAccessCmd(ENABLE);
for(WaitForOscSource=0;WaitForOscSource<5000;WaitForOscSource++);
/* Wait until last write operation on RTC registers has finished */
// RTC_WaitForSynchro();
RTC_WaitForLastTask();
RCC_ClearFlag();
/* Enable the RTC Second */
RTC_ITConfig(RTC_IT_SEC, ENABLE);
RTC_WaitForLastTask();
/* RTC Enabled */
RCC_RTCCLKCmd(ENABLE);
RTC_WaitForLastTask();
}
}
|