RTC_SLEEP.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // Created by EDZ on 25-9-16.
  3. //
  4. #include "../Inc/RTC_SLEEP.h"
  5. RTC_TimeTypeDef SOS_key_struct = {0};
  6. RTC_TimeTypeDef JUGE_key_struct = {0};
  7. RTC_TimeTypeDef Online_struct = {0};
  8. RTC_TimeTypeDef SOS_struct = {0};
  9. RTC_TimeTypeDef IDLE_struct = {0};
  10. // 单独的RTC时间和日期设置函数
  11. void RTC_SetDateTime(RTC_HandleTypeDef *hrtc, uint8_t hours, uint8_t minutes, uint8_t seconds,
  12. uint8_t weekday, uint8_t month, uint8_t date, uint8_t year) {
  13. RTC_TimeTypeDef sTime = {0};
  14. RTC_DateTypeDef sDate = {0};
  15. // 设置时间
  16. sTime.Hours = hours;
  17. sTime.Minutes = minutes;
  18. sTime.Seconds = seconds;
  19. HAL_RTC_SetTime(hrtc, &sTime, RTC_FORMAT_BCD);
  20. // 设置日期
  21. sDate.WeekDay = weekday;
  22. sDate.Month = month;
  23. sDate.Date = date;
  24. sDate.Year = year;
  25. HAL_RTC_SetDate(hrtc, &sDate, RTC_FORMAT_BCD);
  26. }
  27. /**
  28. * @brief 设置指定秒数后的闹钟
  29. * @param delay_seconds 延迟秒数(最大支持 24*3600-1 秒,即一天内)
  30. */
  31. void Set_Alarm_After(uint32_t delay_seconds)
  32. {
  33. if (delay_seconds == 0 || delay_seconds >= 24*3600)
  34. {
  35. // 超过 RTC 最大范围,报错或截断
  36. printf("Error: delay_seconds must be 1 ~ 86399\r\n");
  37. return;
  38. }
  39. RTC_TimeTypeDef now;
  40. RTC_DateTypeDef date;
  41. // 读当前时间
  42. HAL_RTC_GetTime(&hrtc, &now, RTC_FORMAT_BIN);
  43. HAL_RTC_GetDate(&hrtc, &date, RTC_FORMAT_BIN); // 必须读 Date 解锁
  44. // 将当前时间转换为总秒数
  45. uint32_t now_seconds = now.Hours * 3600 + now.Minutes * 60 + now.Seconds;
  46. // 计算目标时间总秒数
  47. uint32_t alarm_seconds = now_seconds + delay_seconds;
  48. if (alarm_seconds >= 24*3600)
  49. alarm_seconds -= 24*3600; // 跨天处理
  50. // 分解为时分秒
  51. uint8_t hr = alarm_seconds / 3600;
  52. uint8_t min = (alarm_seconds % 3600) / 60;
  53. uint8_t sec = alarm_seconds % 60;
  54. // 设置闹钟
  55. RTC_AlarmTypeDef sAlarm = {0};
  56. sAlarm.AlarmTime.Hours = hr;
  57. sAlarm.AlarmTime.Minutes = min;
  58. sAlarm.AlarmTime.Seconds = sec;
  59. sAlarm.Alarm = RTC_ALARM_A;
  60. if (HAL_RTC_SetAlarm_IT(&hrtc, &sAlarm, RTC_FORMAT_BIN) != HAL_OK)
  61. {
  62. Error_Handler();
  63. }
  64. // printf("Now : %02d:%02d:%02d\r\n", now.Hours, now.Minutes, now.Seconds);
  65. // printf("NextAlarm: %02d:%02d:%02d\r\n", hr, min, sec);
  66. // /* 进入 STANDBY 模式 */
  67. __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU); // 清除唤醒标志
  68. HAL_PWR_EnterSTANDBYMode(); // MCU 进入 STANDBY
  69. }