diff --git a/src/runtime/runtime_nrf.c b/src/runtime/runtime_nrf.c index 2271bf25..b0be67b5 100644 --- a/src/runtime/runtime_nrf.c +++ b/src/runtime/runtime_nrf.c @@ -17,6 +17,35 @@ void uart_send(uint8_t c) { NRF_UART0->EVENTS_TXDRDY = 0; } +void rtc_init() { + // Make sure the low-frequency clock is running. + NRF_CLOCK->TASKS_LFCLKSTART = 1; + while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0) {} + NRF_CLOCK->EVENTS_LFCLKSTARTED = 0; + + NRF_RTC0->TASKS_START = 1; + NVIC_SetPriority(RTC0_IRQn, 3); + NVIC_EnableIRQ(RTC0_IRQn); +} + +static volatile bool rtc_wakeup; + +void rtc_sleep(uint32_t ticks) { + NRF_RTC0->INTENSET = RTC_INTENSET_COMPARE0_Msk; + rtc_wakeup = false; + NRF_RTC0->TASKS_CLEAR = 1; + NRF_RTC0->CC[0] = ticks; + while (!rtc_wakeup) { + __WFI(); + } +} + +void RTC0_IRQHandler() { + NRF_RTC0->INTENCLR = RTC_INTENSET_COMPARE0_Msk; + NRF_RTC0->EVENTS_COMPARE[0] = 0; + rtc_wakeup = true; +} + void _start() { main(); } diff --git a/src/runtime/runtime_nrf.go b/src/runtime/runtime_nrf.go index 447ad28d..cb3d1550 100644 --- a/src/runtime/runtime_nrf.go +++ b/src/runtime/runtime_nrf.go @@ -8,6 +8,7 @@ import "C" func init() { C.uart_init(6) // pin_tx = 6, for NRF52840-DK + C.rtc_init() } const Microsecond = 1 @@ -17,7 +18,7 @@ func putchar(c byte) { } func Sleep(d Duration) { - // TODO + C.rtc_sleep(C.uint32_t(d / 32)) // TODO: not accurate (must be d / 30.5175...) } func abort() { diff --git a/src/runtime/runtime_nrf.h b/src/runtime/runtime_nrf.h index 79c25806..61acc3f5 100644 --- a/src/runtime/runtime_nrf.h +++ b/src/runtime/runtime_nrf.h @@ -5,3 +5,6 @@ void uart_init(uint32_t pin_tx); void uart_send(uint8_t c); + +void rtc_init(); +void rtc_sleep(uint32_t ticks);