app_rtc.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include "app_rtc.h"
  2. #include "rtc.h"
  3. #include "time.h"
  4. #include "string.h"
  5. int rtc_get_time(rtc_time_t *t)
  6. {
  7. RTC_TimeTypeDef sTime;
  8. RTC_DateTypeDef DateToUpdate;
  9. HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BCD);
  10. HAL_RTC_GetDate(&hrtc, &DateToUpdate, RTC_FORMAT_BCD);
  11. t->tm_hour = sTime.Hours;
  12. t->tm_min = sTime.Minutes;
  13. t->tm_sec = sTime.Seconds;
  14. t->tm_year = DateToUpdate.Year;
  15. t->tm_mon = DateToUpdate.Month;
  16. t->tm_mday = DateToUpdate.Date;
  17. return 0;
  18. }
  19. int rtc_set_time(rtc_time_t *t)
  20. {
  21. RTC_TimeTypeDef sTime;
  22. RTC_DateTypeDef DateToUpdate;
  23. sTime.Hours = t->tm_hour;
  24. sTime.Minutes = t->tm_min;
  25. sTime.Seconds = t->tm_sec;
  26. sTime.TimeFormat = RTC_HOURFORMAT_24;
  27. sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  28. sTime.StoreOperation = RTC_STOREOPERATION_RESET;
  29. DateToUpdate.Year = t->tm_year;
  30. DateToUpdate.Month = t->tm_mon;
  31. DateToUpdate.Date = t->tm_mday;
  32. DateToUpdate.WeekDay = 0;
  33. HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD);
  34. HAL_RTC_SetDate(&hrtc, &DateToUpdate, RTC_FORMAT_BCD);
  35. return 0;
  36. }
  37. uint32_t rtc_mktime(rtc_time_t *tim)
  38. {
  39. rtc_time_t temp;
  40. uint8_t *ptr = (uint8_t *)&temp;
  41. struct tm t;
  42. memcpy(&temp, tim, sizeof(rtc_time_t));
  43. // BCD时间转换为HEX
  44. for (int i = 0; i < 6; i++)
  45. {
  46. ptr[i] = (ptr[i] >> 4) * 10 + (ptr[i] & 0x0f);
  47. }
  48. t.tm_year = temp.tm_year + 2000 - 1900;
  49. t.tm_mon = temp.tm_mon - 1;
  50. t.tm_mday = temp.tm_mday;
  51. t.tm_hour = temp.tm_hour;
  52. t.tm_min = temp.tm_min;
  53. t.tm_sec = temp.tm_sec;
  54. return mktime(&t) - 8 * 3600;
  55. }
  56. void rtc_gmtime(rtc_time_t *dt, uint32_t time)
  57. {
  58. struct tm *utc_time;
  59. time_t time_t_value = (time_t)time + 8 * 3600;
  60. // 使用gmtime将时间戳转换为UTC时间
  61. utc_time = gmtime(&time_t_value);
  62. // 将struct tm转换为rtc_time_t
  63. dt->tm_year = utc_time->tm_year + 1900 - 2000; // tm_year是从1900年开始的年数
  64. dt->tm_mon = utc_time->tm_mon + 1; // tm_mon是从0开始的月份
  65. dt->tm_mday = utc_time->tm_mday;
  66. dt->tm_hour = utc_time->tm_hour;
  67. dt->tm_min = utc_time->tm_min;
  68. dt->tm_sec = utc_time->tm_sec;
  69. // 将时间转换为BCD时间
  70. uint8_t *ptr = (uint8_t *)dt;
  71. for (int i = 0; i < 6; i++)
  72. {
  73. ptr[i] = (ptr[i] / 10) * 16 + (ptr[i] % 10);
  74. }
  75. }