本帖最后由 阿源玩电子 于 2025-6-25 20:54 编辑
打印时间戳
1.rtc外设初始化
- <div class="blockcode"><blockquote>void RTC_Configure(void)
- {
-
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_RTC | RCC_APB1Periph_BKP, ENABLE);
- PWR_BackupAccessCmd(ENABLE);
- BKP_DeInit();
- if (BKP_ReadBackupRegister(BKP_DR1) != 0x5D5D)
- {
- RCC_LSEConfig(RCC_LSE_ON);
- while(RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET);
- RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
- RCC_RTCCLKCmd(ENABLE);
- RTC_WaitForSynchro();
- RTC_WaitForLastTask();
- RTC_SetPrescaler(32767);
- RTC_WaitForLastTask();
- uint32_t init_seconds = DateToSeconds(RTC_BASE_YEAR, RTC_BASE_MONTH,
- RTC_BASE_DATE, 0, 0, 0);
- RTC_SetCounter(init_seconds);
- RTC_WaitForLastTask();
- RTC_ITConfig(RTC_IT_SEC, ENABLE);
- RTC_WaitForLastTask();
- BKP_WriteBackupRegister(BKP_DR1, 0x5D5D);
- }
- else
- {
- RTC_WaitForSynchro();
- RTC_ITConfig(RTC_IT_SEC, ENABLE);
- RTC_WaitForLastTask();
- }
- NVIC_InitTypeDef NVIC_InitStruct;
- NVIC_InitStruct.NVIC_IRQChannel = RTC_BKP_IRQn;
- NVIC_InitStruct.NVIC_IRQChannelPriority = 0;
- NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
- NVIC_Init(&NVIC_InitStruct);
- }
2.获取日期函数
- void RTC_GetDate(RTC_DateTypeDef* date)
- {
- uint32_t counter = RTC_GetCounter();
- uint32_t days = counter / 86400;
- date->RTC_WeekDay = (days + RTC_BASE_WEEKDAY) % 7;
- date->RTC_Year = RTC_BASE_YEAR;
- static const uint8_t month_days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
- uint8_t month;
- for (month = 0; month < 12; month++) {
- uint8_t days_in_month = month_days[month];
-
- if (month == 1 && IsLeapYear(RTC_BASE_YEAR)) {
- days_in_month = 29;
- }
-
- if (days >= days_in_month) {
- days -= days_in_month;
- } else {
- break;
- }
- }
- date->RTC_Month = month + 1;
- date->RTC_Date = days + 1;
- }
4.获取时间函数
- void RTC_GetTime(RTC_TimeTypeDef* time)
- {
- uint32_t counter = RTC_GetCounter();
-
- time->RTC_Seconds = counter % 60;
- counter /= 60;
- time->RTC_Minutes = counter % 60;
- counter /= 60;
- time->RTC_Hours = counter % 24;
- }
5.打印函数
- void Get_RTC_Time()
- {
- RTC_DateTypeDef date;
- RTC_TimeTypeDef time;
- uint32_t counter = RTC_GetCounter();
- RTC_GetDate(&date);
- RTC_GetTime(&time);
-
- printf("RTC Counter: %lu\r\n", counter);
- printf("Days: %lu\r\n", counter / 86400);
- printf("Current: %04d-%02d-%02d %02d:%02d:%02d Week:%d\r\n",
- date.RTC_Year, date.RTC_Month, date.RTC_Date,
- time.RTC_Hours, time.RTC_Minutes, time.RTC_Seconds,
- date.RTC_WeekDay);
- }
6.试验现象
|
|