RTC(Real_Time Clock)实时时钟,用于得到年、月、日、时、分、秒等时间日期信息。目前几乎已经是统一标准了,如图,32.768K经过15次分频后,恰好是1秒,其它时间只要在1秒频率下计数即可,RTC本质上就是一个1秒计数器。为了方便程序使用,内部会转化成年月日时分秒格式存储,并提供通信接口
static RTC_FirstInit(VOID)
{
DRV_TRACE("First power on need to configure RTC.");
/* 选择晶振LSE,低速外部晶振,即32.768Khz */
RCC_RTCCLKConfig(RCC_RTCCLKSOURCE_LSE);
RCC_LSEConfig(RCC_LSE_EN);
while (RCC_GetBitState(RCC_FLAG_LSESTB) == RESET)
{
}
RCC_RTCCLK_Enable(ENABLE);
RTC_WaitRSF();
RTC_WaitLWOFF();
/* 分频,即1Hz */
RTC_SetPrescaler(32768-1); /* 1s */
RTC_WaitLWOFF();
}
static time_t RTC_SetTime(VOID)
{
U32 year = 0xFF;
U32 mon = 0xFF;
U32 day = 0xFF;
U32 hour = 0xFF;
U32 min = 0xFF;
U32 sec = 0xFF;
struct tm t;
memset(&t, 0, sizeof(t));
printf("Please Set Time:\r\n");
printf("Please input year:\r\n");
scanf("%u", &year);
printf("year:%u\r\n", year);
printf("Please input mon:\r\n");
scanf("%u", &mon);
printf("mon:%u\r\n", mon);
printf("Please input day:\r\n");
scanf("%u", &day);
printf("day:%u\r\n", day);
printf("Please input hour:\r\n");
scanf("%u", &hour);
printf("hour:%u\r\n", hour);
printf("Please input min:\r\n");
scanf("%u", &min);
printf("min:%u\r\n", min);
printf("Please input sec:\r\n");
scanf("%u", &sec);
printf("sec:%u\r\n", sec);
t.tm_sec = sec;
t.tm_min = min;
t.tm_hour = hour;
t.tm_mday = day;
t.tm_mon = mon-1; /* 0-11 */
t.tm_year = year-1900; /* 从1900年开始开始计算的 */
APP_DEBUG("%u-%u-%u %u:%u:%u", t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
return(mktime(&t));
}
VOID DRV_RTC_TimeAdjust(IN U32 sec)
{
RTC_WaitLWOFF();
RTC_SetCounter(sec);
RTC_WaitLWOFF();
}
#define time DRV_RTC_GetTime
time_t DRV_RTC_GetTime(time_t *timer)
{
U32 c = 0;
c = RTC_GetCounter();
if (timer != NULL)
{
*timer = c;
}
return c;
}
VOID APP_RTC_Test(VOID)
{
BOOL firstBootFlag = FALSE;
time_t now = 0;
DRV_POWER_DumpBootReason();
firstBootFlag = DRV_POWER_IsFirstBoot();
DRV_RTC_Init(firstBootFlag);
if (TRUE == firstBootFlag)
{
DRV_RTC_TimeAdjust(RTC_SetTime());
}
while(1)
{
APP_Delay(1000);
now = time(NULL);
printf("%s", ctime(&now));
}
} |