|
30 | 30 |
|
31 | 31 | #include "imxrt.h" |
32 | 32 | #include "debug/printf.h" |
33 | | -#include <sys/time.h> // for struct timeval |
| 33 | +#include <sys/time.h> // for struct timeval and struct timezone |
34 | 34 |
|
35 | 35 | unsigned long rtc_get(void) |
36 | 36 | { |
@@ -88,3 +88,50 @@ int _gettimeofday(struct timeval *tv, void *ignore __attribute__((unused))) |
88 | 88 | lo1 = lo2; |
89 | 89 | } |
90 | 90 | } |
| 91 | + |
| 92 | +__attribute__((weak)) |
| 93 | +int settimeofday(const struct timeval *const tv, |
| 94 | + const struct timezone *const tz __attribute__((unused))) { |
| 95 | + // Stop the RTC |
| 96 | + SNVS_HPCR &= ~(SNVS_HPCR_RTC_EN | SNVS_HPCR_HP_TS); |
| 97 | + while (SNVS_HPCR & SNVS_HPCR_RTC_EN) { |
| 98 | + // Wait |
| 99 | + } |
| 100 | + |
| 101 | + // Stop the SRTC |
| 102 | + SNVS_LPCR &= ~SNVS_LPCR_SRTC_ENV; |
| 103 | + while (SNVS_LPCR & SNVS_LPCR_SRTC_ENV) { |
| 104 | + // Wait |
| 105 | + } |
| 106 | + |
| 107 | + // Set the SRTC |
| 108 | + // Notes: |
| 109 | + // * The type of tv_usec is suseconds_t, range is [-1, 1000000] |
| 110 | + // * There are 32768 ticks per 1,000,000 microseconds; that's where 512/15625 |
| 111 | + // comes from, it's 32768/1000000 in lowest terms |
| 112 | + // Refs: |
| 113 | + // * https://pubs.opengroup.org/onlinepubs/007904975/basedefs/sys/time.h.html |
| 114 | + // * https://pubs.opengroup.org/onlinepubs/007904975/basedefs/sys/types.h.html |
| 115 | + uint32_t sec = (uint32_t)tv->tv_sec; |
| 116 | + uint32_t usec = (uint32_t)tv->tv_usec; |
| 117 | + if (usec == 1000000) { |
| 118 | + sec++; |
| 119 | + usec = 0; |
| 120 | + } else if (usec == UINT32_MAX) { |
| 121 | + sec--; |
| 122 | + usec = 999999; |
| 123 | + } |
| 124 | + SNVS_LPSRTCLR = (sec << 15) | (((usec << 9) / 15625) & 0x7fff); |
| 125 | + SNVS_LPSRTCMR = (sec >> 17) & 0x7fff; |
| 126 | + |
| 127 | + // Start the SRTC |
| 128 | + SNVS_LPCR |= SNVS_LPCR_SRTC_ENV; |
| 129 | + while (!(SNVS_LPCR & SNVS_LPCR_SRTC_ENV)) { |
| 130 | + // Wait |
| 131 | + } |
| 132 | + |
| 133 | + // Start the RTC and sync it to the SRTC |
| 134 | + SNVS_HPCR |= SNVS_HPCR_RTC_EN | SNVS_HPCR_HP_TS; |
| 135 | + |
| 136 | + return 0; |
| 137 | +} |
0 commit comments