3535#include "nrfx_rtc.h"
3636#include "nrf_clock.h"
3737
38+ // We clock the RTC very slowly (8Hz) so that it won't overflow often.
39+ // But the counter is only 24 bits, so overflow is about every 24 days ...
40+ // For testing, set this to 32768 and it'll overflow every few minutes
41+
3842#define RTC_CLOCK_HZ (8)
3943
40- static uint32_t rtc_offset = 0 ;
44+ volatile static uint32_t rtc_offset = 0 ;
45+ int8_t rtc_calibration = 0 ;
4146
4247const nrfx_rtc_t rtc_instance = NRFX_RTC_INSTANCE (0 );
4348
@@ -49,7 +54,9 @@ const nrfx_rtc_config_t rtc_config = {
4954};
5055
5156void rtc_handler (nrfx_rtc_int_type_t int_type ) {
52- // do nothing
57+ if (int_type == NRFX_RTC_INT_OVERFLOW ) {
58+ rtc_offset += (1L <<24 ) / RTC_CLOCK_HZ ;
59+ }
5360}
5461
5562void rtc_init (void ) {
@@ -59,6 +66,7 @@ void rtc_init(void) {
5966 nrfx_rtc_counter_clear (& rtc_instance );
6067 nrfx_rtc_init (& rtc_instance , & rtc_config , rtc_handler );
6168 nrfx_rtc_enable (& rtc_instance );
69+ nrfx_rtc_overflow_enable (& rtc_instance , 1 );
6270}
6371
6472void common_hal_rtc_get_time (timeutils_struct_time_t * tm ) {
@@ -75,8 +83,11 @@ void common_hal_rtc_set_time(timeutils_struct_time_t *tm) {
7583
7684// A positive value speeds up the clock by removing clock cycles.
7785int common_hal_rtc_get_calibration (void ) {
78- return 0 ;
86+ return rtc_calibration ;
7987}
8088
8189void common_hal_rtc_set_calibration (int calibration ) {
90+ if (calibration > 127 || calibration < -127 )
91+ mp_raise_ValueError (translate ("calibration value out of range +/-127" ));
92+ rtc_calibration = calibration ;
8293}
0 commit comments