Skip to content

Commit 54589de

Browse files
authored
Merge pull request #6004 from dhalbert/samd-rtc-count-overflow
fetch RTC count more atomically
2 parents c234d92 + b18b0fd commit 54589de

File tree

1 file changed

+23
-13
lines changed
  • ports/atmel-samd/supervisor

1 file changed

+23
-13
lines changed

ports/atmel-samd/supervisor/port.c

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -498,21 +498,31 @@ uint32_t port_get_saved_word(void) {
498498
static volatile uint64_t overflowed_ticks = 0;
499499

500500
static uint32_t _get_count(uint64_t *overflow_count) {
501-
#ifdef SAM_D5X_E5X
502-
while ((RTC->MODE0.SYNCBUSY.reg & (RTC_MODE0_SYNCBUSY_COUNTSYNC | RTC_MODE0_SYNCBUSY_COUNT)) != 0) {
503-
}
504-
#endif
505-
// SAMD21 does continuous sync so we don't need to wait here.
501+
while(1) {
502+
// Disable interrupts so we can grab the count and the overflow atomically.
503+
common_hal_mcu_disable_interrupts();
506504

507-
// Disable interrupts so we can grab the count and the overflow.
508-
common_hal_mcu_disable_interrupts();
509-
uint32_t count = RTC->MODE0.COUNT.reg;
510-
if (overflow_count != NULL) {
511-
*overflow_count = overflowed_ticks;
512-
}
513-
common_hal_mcu_enable_interrupts();
505+
#ifdef SAM_D5X_E5X
506+
while ((RTC->MODE0.SYNCBUSY.reg & (RTC_MODE0_SYNCBUSY_COUNTSYNC | RTC_MODE0_SYNCBUSY_COUNT)) != 0) {
507+
}
508+
#endif
509+
// SAMD21 does continuous sync so we don't need to wait here.
510+
511+
uint32_t count = RTC->MODE0.COUNT.reg;
512+
if (overflow_count != NULL) {
513+
*overflow_count = overflowed_ticks;
514+
}
515+
516+
bool overflow_pending = RTC->MODE0.INTFLAG.bit.OVF;
514517

515-
return count;
518+
common_hal_mcu_enable_interrupts();
519+
520+
if (!overflow_pending) {
521+
return count;
522+
}
523+
524+
// Try again if overflow hasn't been processed yet.
525+
}
516526
}
517527

518528
volatile bool _woken_up;

0 commit comments

Comments
 (0)