drv_rtc.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2024-01-13 ChuShicheng first version
  9. */
  10. #include "board.h"
  11. #include <rtdevice.h>
  12. #include "hardware/rtc.h"
  13. #include "pico/util/datetime.h"
  14. #define DBG_LEVEL DBG_LOG
  15. #include <rtdbg.h>
  16. #define LOG_TAG "DRV.RTC"
  17. struct rtc_device_object
  18. {
  19. rt_rtc_dev_t rtc_dev;
  20. };
  21. static struct rtc_device_object rtc_device;
  22. static rt_err_t pico_rtc_get_timeval(struct timeval *tv)
  23. {
  24. datetime_t t;
  25. struct tm tm_new = {0};
  26. rtc_get_datetime(&t);
  27. tm_new.tm_sec = t.sec;
  28. tm_new.tm_min = t.min;
  29. tm_new.tm_hour = t.hour;
  30. tm_new.tm_wday = t.dotw;
  31. tm_new.tm_mday = t.day;
  32. tm_new.tm_mon = t.month - 1;
  33. tm_new.tm_year = t.year - 1900;
  34. tv->tv_sec = timegm(&tm_new);
  35. return RT_EOK;
  36. }
  37. static rt_err_t pico_rtc_init(void)
  38. {
  39. rtc_init();
  40. datetime_t t;
  41. t.sec = 0 ;
  42. t.min = 0;
  43. t.hour = 0;
  44. t.day = 01;
  45. t.month = 01;
  46. t.year = 1970;
  47. t.dotw = 4;
  48. rtc_set_datetime(&t);
  49. return RT_EOK;
  50. }
  51. static rt_err_t pico_rtc_get_secs(time_t *sec)
  52. {
  53. struct timeval tv;
  54. pico_rtc_get_timeval(&tv);
  55. *(time_t *) sec = tv.tv_sec;
  56. LOG_D("RTC: get rtc_time %d", *sec);
  57. return RT_EOK;
  58. }
  59. static rt_err_t pico_rtc_set_secs(time_t *sec)
  60. {
  61. rt_err_t result = RT_EOK;
  62. datetime_t t;
  63. struct tm tm = {0};
  64. gmtime_r(sec, &tm);
  65. t.sec = tm.tm_sec ;
  66. t.min = tm.tm_min ;
  67. t.hour = tm.tm_hour;
  68. t.day = tm.tm_mday;
  69. t.month = tm.tm_mon + 1;
  70. t.year = tm.tm_year + 1900;
  71. t.dotw = tm.tm_wday;
  72. rtc_set_datetime(&t);
  73. LOG_D("RTC: set rtc_time");
  74. #ifdef RT_USING_ALARM
  75. rt_alarm_update(&rtc_device.rtc_dev.parent, 1);
  76. #endif
  77. return result;
  78. }
  79. static const struct rt_rtc_ops pico_rtc_ops =
  80. {
  81. pico_rtc_init,
  82. pico_rtc_get_secs,
  83. pico_rtc_set_secs,
  84. RT_NULL,
  85. RT_NULL,
  86. pico_rtc_get_timeval,
  87. RT_NULL,
  88. };
  89. static int rt_hw_rtc_init(void)
  90. {
  91. rt_err_t result;
  92. rtc_device.rtc_dev.ops = &pico_rtc_ops;
  93. result = rt_hw_rtc_register(&rtc_device.rtc_dev, "rtc", RT_DEVICE_FLAG_RDWR, RT_NULL);
  94. if (result != RT_EOK)
  95. {
  96. LOG_E("rtc register err code: %d", result);
  97. return result;
  98. }
  99. LOG_D("rtc init success");
  100. return RT_EOK;
  101. }
  102. INIT_DEVICE_EXPORT(rt_hw_rtc_init);