| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- #include "app_rtc.h"
- #include "rtc.h"
- #include "time.h"
- #include "string.h"
- int rtc_get_time(rtc_time_t *t)
- {
- RTC_TimeTypeDef sTime;
- RTC_DateTypeDef DateToUpdate;
- HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BCD);
- HAL_RTC_GetDate(&hrtc, &DateToUpdate, RTC_FORMAT_BCD);
- t->tm_hour = sTime.Hours;
- t->tm_min = sTime.Minutes;
- t->tm_sec = sTime.Seconds;
- t->tm_year = DateToUpdate.Year;
- t->tm_mon = DateToUpdate.Month;
- t->tm_mday = DateToUpdate.Date;
- return 0;
- }
- int rtc_set_time(rtc_time_t *t)
- {
- RTC_TimeTypeDef sTime;
- RTC_DateTypeDef DateToUpdate;
- sTime.Hours = t->tm_hour;
- sTime.Minutes = t->tm_min;
- sTime.Seconds = t->tm_sec;
- sTime.TimeFormat = RTC_HOURFORMAT_24;
- sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
- sTime.StoreOperation = RTC_STOREOPERATION_RESET;
- DateToUpdate.Year = t->tm_year;
- DateToUpdate.Month = t->tm_mon;
- DateToUpdate.Date = t->tm_mday;
- DateToUpdate.WeekDay = 0;
- HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD);
- HAL_RTC_SetDate(&hrtc, &DateToUpdate, RTC_FORMAT_BCD);
- return 0;
- }
- uint32_t rtc_mktime(rtc_time_t *tim)
- {
- rtc_time_t temp;
- uint8_t *ptr = (uint8_t *)&temp;
- struct tm t;
- memcpy(&temp, tim, sizeof(rtc_time_t));
- // BCD时间转换为HEX
- for (int i = 0; i < 6; i++)
- {
- ptr[i] = (ptr[i] >> 4) * 10 + (ptr[i] & 0x0f);
- }
- t.tm_year = temp.tm_year + 2000 - 1900;
- t.tm_mon = temp.tm_mon - 1;
- t.tm_mday = temp.tm_mday;
- t.tm_hour = temp.tm_hour;
- t.tm_min = temp.tm_min;
- t.tm_sec = temp.tm_sec;
- return mktime(&t) - 8 * 3600;
- }
- void rtc_gmtime(rtc_time_t *dt, uint32_t time)
- {
- struct tm *utc_time;
- time_t time_t_value = (time_t)time + 8 * 3600;
- // 使用gmtime将时间戳转换为UTC时间
- utc_time = gmtime(&time_t_value);
- // 将struct tm转换为rtc_time_t
- dt->tm_year = utc_time->tm_year + 1900 - 2000; // tm_year是从1900年开始的年数
- dt->tm_mon = utc_time->tm_mon + 1; // tm_mon是从0开始的月份
- dt->tm_mday = utc_time->tm_mday;
- dt->tm_hour = utc_time->tm_hour;
- dt->tm_min = utc_time->tm_min;
- dt->tm_sec = utc_time->tm_sec;
- // 将时间转换为BCD时间
- uint8_t *ptr = (uint8_t *)dt;
- for (int i = 0; i < 6; i++)
- {
- ptr[i] = (ptr[i] / 10) * 16 + (ptr[i] % 10);
- }
- }
|