Skip to content

Commit 28254de

Browse files
committed
#1046 handle overflows in the RTC counter
1 parent ff6395f commit 28254de

File tree

1 file changed

+14
-3
lines changed
  • ports/nrf/common-hal/rtc

1 file changed

+14
-3
lines changed

ports/nrf/common-hal/rtc/RTC.c

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,14 @@
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

4247
const nrfx_rtc_t rtc_instance = NRFX_RTC_INSTANCE(0);
4348

@@ -49,7 +54,9 @@ const nrfx_rtc_config_t rtc_config = {
4954
};
5055

5156
void 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

5562
void 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

6472
void 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.
7785
int common_hal_rtc_get_calibration(void) {
78-
return 0;
86+
return rtc_calibration;
7987
}
8088

8189
void 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

Comments
 (0)