From 3b39ab07e5b52acfe2ba7aa7f92cfa3c859d3dd7 Mon Sep 17 00:00:00 2001 From: Dario Nieuwenhuis Date: Thu, 24 Sep 2020 19:59:20 +0200 Subject: [PATCH] Add 64-bit rtc driver with alarm support. --- embassy-nrf/src/lib.rs | 1 + embassy-nrf/src/rtc.rs | 204 ++++++++++++++++++++++++++++++++++++ examples/src/bin/rtc_raw.rs | 55 ++++++++++ 3 files changed, 260 insertions(+) create mode 100644 embassy-nrf/src/rtc.rs create mode 100644 examples/src/bin/rtc_raw.rs diff --git a/embassy-nrf/src/lib.rs b/embassy-nrf/src/lib.rs index 4e6da8c3..578d7663 100644 --- a/embassy-nrf/src/lib.rs +++ b/embassy-nrf/src/lib.rs @@ -40,6 +40,7 @@ pub use nrf52840_pac as pac; pub mod gpiote; pub mod interrupt; pub mod qspi; +pub mod rtc; pub mod uarte; pub use cortex_m_rt::interrupt; diff --git a/embassy-nrf/src/rtc.rs b/embassy-nrf/src/rtc.rs new file mode 100644 index 00000000..a5810eb5 --- /dev/null +++ b/embassy-nrf/src/rtc.rs @@ -0,0 +1,204 @@ +use core::cell::Cell; +use core::ops::Deref; +use core::sync::atomic::{AtomicU32, Ordering}; + +use defmt::trace; + +use crate::interrupt; +use crate::interrupt::Mutex; +use crate::pac::{rtc0, Interrupt, RTC0, RTC1}; + +#[cfg(any(feature = "52832", feature = "52833", feature = "52840"))] +use crate::pac::RTC2; + +fn calc_now(period: u32, counter: u32) -> u64 { + let shift = ((period & 1) << 23) + 0x400000; + let counter_shifted = (counter + shift) & 0xFFFFFF; + ((period as u64) << 23) + counter_shifted as u64 - 0x400000 +} + +mod test { + use super::*; + + #[test] + fn test_calc_now() { + assert_eq!(calc_now(0, 0x000000), 0x0_000000); + assert_eq!(calc_now(0, 0x000001), 0x0_000001); + assert_eq!(calc_now(0, 0x7FFFFF), 0x0_7FFFFF); + assert_eq!(calc_now(1, 0x7FFFFF), 0x0_7FFFFF); + assert_eq!(calc_now(0, 0x800000), 0x0_800000); + assert_eq!(calc_now(1, 0x800000), 0x0_800000); + assert_eq!(calc_now(1, 0x800001), 0x0_800001); + assert_eq!(calc_now(1, 0xFFFFFF), 0x0_FFFFFF); + assert_eq!(calc_now(2, 0xFFFFFF), 0x0_FFFFFF); + assert_eq!(calc_now(1, 0x000000), 0x1_000000); + assert_eq!(calc_now(2, 0x000000), 0x1_000000); + } +} + +pub struct RTC { + rtc: T, + + /// Number of 2^23 periods elapsed since boot. + /// + /// This is incremented by 1 + /// - on overflow (counter value 0) + /// - on "midway" between overflows (at counter value 0x800000) + /// + /// Therefore: When even, counter is in 0..0x7fffff. When odd, counter is in 0x800000..0xFFFFFF + /// This allows for now() to return the correct value even if it races an overflow. + /// + /// It overflows on 2^32 * 2^23 / 32768 seconds of uptime, which is 34865 years. + period: AtomicU32, + + /// Timestamp at which to fire alarm. u64::MAX if no alarm is scheduled. + alarm: Mutex>, +} + +impl RTC { + pub fn new(rtc: T) -> Self { + Self { + rtc, + period: AtomicU32::new(0), + alarm: Mutex::new(Cell::new(u64::MAX)), + } + } + + pub fn start(&'static self) { + self.rtc.cc[0].write(|w| unsafe { w.bits(0x800000) }); + + self.rtc.intenset.write(|w| { + let w = w.ovrflw().set(); + let w = w.compare0().set(); + w + }); + + self.rtc.tasks_clear.write(|w| w.tasks_clear().set_bit()); + self.rtc.tasks_start.write(|w| w.tasks_start().set_bit()); + + // Wait for clear + while self.rtc.counter.read().bits() != 0 {} + + T::set_rtc_instance(self); + interrupt::enable(T::INTERRUPT); + } + + fn on_interrupt(&self) { + if self.rtc.events_ovrflw.read().bits() == 1 { + self.rtc.events_ovrflw.write(|w| w); + trace!("rtc overflow"); + self.next_period(); + } + + if self.rtc.events_compare[0].read().bits() == 1 { + self.rtc.events_compare[0].write(|w| w); + trace!("rtc compare0"); + self.next_period(); + } + + if self.rtc.events_compare[1].read().bits() == 1 { + self.rtc.events_compare[1].write(|w| w); + trace!("rtc compare1"); + self.trigger_alarm(); + } + } + + fn next_period(&self) { + interrupt::free(|cs| { + let period = self.period.fetch_add(1, Ordering::Relaxed) + 1; + let t = (period as u64) << 23; + + let at = self.alarm.borrow(cs).get(); + + let diff = at - t; + if diff < 0xc00000 { + self.rtc.cc[1].write(|w| unsafe { w.bits(at as u32 & 0xFFFFFF) }); + self.rtc.intenset.write(|w| w.compare1().set()); + } + }) + } + + pub fn now(&self) -> u64 { + let counter = self.rtc.counter.read().bits(); + let period = self.period.load(Ordering::Relaxed); + calc_now(period, counter) + } + + fn trigger_alarm(&self) { + self.rtc.intenclr.write(|w| w.compare1().clear()); + interrupt::free(|cs| self.alarm.borrow(cs).set(u64::MAX)); + + // TODO + trace!("ALARM! {:u32}", self.now() as u32); + } + + pub fn set_alarm(&self, at: u64) { + interrupt::free(|cs| { + let t = self.now(); + if at <= t { + self.trigger_alarm(); + return; + } + + self.alarm.borrow(cs).set(at); + + let diff = at - t; + if diff < 0xc00000 { + self.rtc.cc[1].write(|w| unsafe { w.bits(at as u32 & 0xFFFFFF) }); + self.rtc.intenset.write(|w| w.compare1().set()); + + // We may have been preempted for arbitrary time between checking if `at` is in the past + // and setting the cc. In that case, we don't know if the cc has triggered. + // So, we check again just in case. + + let t = self.now(); + if at <= t { + self.trigger_alarm(); + return; + } + } else { + self.rtc.intenclr.write(|w| w.compare1().clear()); + } + }) + } + + pub fn clear_alarm(&self) { + self.set_alarm(u64::MAX); + } +} + +/// Implemented by all RTC instances. +pub trait Instance: Deref + Sized { + /// The interrupt associated with this RTC instance. + const INTERRUPT: Interrupt; + + fn set_rtc_instance(rtc: &'static RTC); + fn get_rtc_instance() -> &'static RTC; +} + +macro_rules! impl_instance { + ($name:ident, $static_name:ident) => { + static mut $static_name: Option<&'static RTC<$name>> = None; + + impl Instance for $name { + const INTERRUPT: Interrupt = Interrupt::$name; + fn set_rtc_instance(rtc: &'static RTC) { + unsafe { $static_name = Some(rtc) } + } + fn get_rtc_instance() -> &'static RTC { + unsafe { $static_name.unwrap() } + } + } + + #[interrupt] + fn $name() { + $name::get_rtc_instance().on_interrupt(); + } + }; +} + +impl_instance!(RTC0, RTC0_INSTANCE); +impl_instance!(RTC1, RTC1_INSTANCE); + +#[cfg(any(feature = "52832", feature = "52833", feature = "52840"))] +impl_instance!(RTC2, RTC2_INSTANCE); diff --git a/examples/src/bin/rtc_raw.rs b/examples/src/bin/rtc_raw.rs new file mode 100644 index 00000000..041bbaf0 --- /dev/null +++ b/examples/src/bin/rtc_raw.rs @@ -0,0 +1,55 @@ +#![no_std] +#![no_main] +#![feature(type_alias_impl_trait)] + +#[path = "../example_common.rs"] +mod example_common; +use example_common::*; + +use core::mem::MaybeUninit; +use cortex_m_rt::entry; +use embassy_nrf::rtc; +use nrf52840_hal::clocks; + +static mut RTC: MaybeUninit> = MaybeUninit::uninit(); + +#[entry] +fn main() -> ! { + info!("Hello World!"); + + let p = embassy_nrf::pac::Peripherals::take().dewrap(); + + clocks::Clocks::new(p.CLOCK) + .enable_ext_hfosc() + .set_lfclk_src_external(clocks::LfOscConfiguration::NoExternalNoBypass) + .start_lfclk(); + + let rtc: &'static _ = unsafe { + let ptr = RTC.as_mut_ptr(); + ptr.write(rtc::RTC::new(p.RTC1)); + &*ptr + }; + + rtc.start(); + rtc.set_alarm(53719); + + info!("initialized!"); + + let mut val = 0; + let mut printval = 0; + loop { + let val2 = rtc.now(); + if val2 < val { + info!( + "timer ran backwards! {:u32} -> {:u32}", + val as u32, val2 as u32 + ); + } + val = val2; + + if val > printval + 32768 { + info!("tick {:u32}", val as u32); + printval = val; + } + } +}