use core::sync::atomic::{AtomicU8, Ordering};
use fugit::{MicrosDurationU32, MicrosDurationU64, TimerInstantU64};
use crate::{
atomic_register_access::{write_bitmask_clear, write_bitmask_set},
clocks::ClocksManager,
pac::{self, RESETS, TIMER},
resets::SubsystemReset,
typelevel::Sealed,
};
pub type Instant = TimerInstantU64<1_000_000>;
static ALARMS: AtomicU8 = AtomicU8::new(0x0F);
fn take_alarm(mask: u8) -> bool {
critical_section::with(|_| {
let alarms = ALARMS.load(Ordering::Relaxed);
ALARMS.store(alarms & !mask, Ordering::Relaxed);
(alarms & mask) != 0
})
}
fn release_alarm(mask: u8) {
critical_section::with(|_| {
let alarms = ALARMS.load(Ordering::Relaxed);
ALARMS.store(alarms | mask, Ordering::Relaxed);
});
}
#[derive(Clone, Copy)]
pub struct Timer {
_private: (),
}
impl Timer {
pub fn new(timer: TIMER, resets: &mut RESETS, _clocks: &ClocksManager) -> Self {
timer.reset_bring_down(resets);
timer.reset_bring_up(resets);
Self { _private: () }
}
pub fn get_counter(&self) -> Instant {
let timer = unsafe { &*pac::TIMER::PTR };
let mut hi0 = timer.timerawh().read().bits();
let timestamp = loop {
let low = timer.timerawl().read().bits();
let hi1 = timer.timerawh().read().bits();
if hi0 == hi1 {
break (u64::from(hi0) << 32) | u64::from(low);
}
hi0 = hi1;
};
TimerInstantU64::from_ticks(timestamp)
}
pub fn get_counter_low(&self) -> u32 {
unsafe { &*pac::TIMER::PTR }.timerawl().read().bits()
}
pub fn count_down(&self) -> CountDown {
CountDown {
timer: *self,
period: MicrosDurationU64::nanos(0),
next_end: None,
}
}
pub fn alarm_0(&mut self) -> Option<Alarm0> {
take_alarm(1 << 0).then_some(Alarm0(*self))
}
pub fn alarm_1(&mut self) -> Option<Alarm1> {
take_alarm(1 << 1).then_some(Alarm1(*self))
}
pub fn alarm_2(&mut self) -> Option<Alarm2> {
take_alarm(1 << 2).then_some(Alarm2(*self))
}
pub fn alarm_3(&mut self) -> Option<Alarm3> {
take_alarm(1 << 3).then_some(Alarm3(*self))
}
fn delay_us_internal(&self, mut us: u32) {
let mut start = self.get_counter_low();
loop {
let now = self.get_counter_low();
let waited = now.wrapping_sub(start);
if waited >= us {
break;
}
start = now;
us -= waited;
}
}
}
macro_rules! impl_delay_traits {
($($t:ty),+) => {
$(
impl embedded_hal_0_2::blocking::delay::DelayUs<$t> for Timer {
fn delay_us(&mut self, us: $t) {
#![allow(unused_comparisons)]
assert!(us >= 0); self.delay_us_internal(us as u32)
}
}
impl embedded_hal_0_2::blocking::delay::DelayMs<$t> for Timer {
fn delay_ms(&mut self, ms: $t) {
#![allow(unused_comparisons)]
assert!(ms >= 0); for _ in 0..ms {
self.delay_us_internal(1000);
}
}
}
)*
}
}
impl_delay_traits!(u8, u16, u32, i32);
impl embedded_hal::delay::DelayNs for Timer {
fn delay_ns(&mut self, ns: u32) {
let us = ns.div_ceil(1000);
self.delay_us_internal(us)
}
fn delay_us(&mut self, us: u32) {
self.delay_us_internal(us)
}
fn delay_ms(&mut self, ms: u32) {
for _ in 0..ms {
self.delay_us_internal(1000);
}
}
}
pub struct CountDown {
timer: Timer,
period: MicrosDurationU64,
next_end: Option<u64>,
}
impl embedded_hal_0_2::timer::CountDown for CountDown {
type Time = MicrosDurationU64;
fn start<T>(&mut self, count: T)
where
T: Into<Self::Time>,
{
self.period = count.into();
self.next_end = Some(
self.timer
.get_counter()
.ticks()
.wrapping_add(self.period.to_micros()),
);
}
fn wait(&mut self) -> nb::Result<(), void::Void> {
if let Some(end) = self.next_end {
let ts = self.timer.get_counter().ticks();
if ts >= end {
self.next_end = Some(end.wrapping_add(self.period.to_micros()));
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
} else {
panic!("CountDown is not running!");
}
}
}
impl embedded_hal_0_2::timer::Periodic for CountDown {}
impl embedded_hal_0_2::timer::Cancel for CountDown {
type Error = &'static str;
fn cancel(&mut self) -> Result<(), Self::Error> {
if self.next_end.is_none() {
Err("CountDown is not running.")
} else {
self.next_end = None;
Ok(())
}
}
}
pub trait Alarm: Sealed {
fn clear_interrupt(&mut self);
fn enable_interrupt(&mut self);
fn disable_interrupt(&mut self);
fn schedule(&mut self, countdown: MicrosDurationU32) -> Result<(), ScheduleAlarmError>;
fn schedule_at(&mut self, timestamp: Instant) -> Result<(), ScheduleAlarmError>;
fn finished(&self) -> bool;
fn cancel(&mut self) -> Result<(), ScheduleAlarmError>;
}
macro_rules! impl_alarm {
($name:ident { rb: $timer_alarm:ident, int: $int_alarm:ident, int_name: $int_name:tt, armed_bit_mask: $armed_bit_mask: expr }) => {
pub struct $name(Timer);
impl $name {
fn schedule_internal(&mut self, timestamp: Instant) -> Result<(), ScheduleAlarmError> {
let timestamp_low = (timestamp.ticks() & 0xFFFF_FFFF) as u32;
let timer = unsafe { &*pac::TIMER::PTR };
cortex_m::interrupt::free(|_| {
let alarm = &timer.$timer_alarm();
alarm.write(|w| unsafe { w.bits(timestamp_low) });
let now = self.0.get_counter();
if now > timestamp && (timer.armed().read().bits() & $armed_bit_mask) != 0 {
unsafe {
timer.armed().write_with_zero(|w| w.bits($armed_bit_mask));
crate::atomic_register_access::write_bitmask_set(
timer.intf().as_ptr(),
$armed_bit_mask,
);
}
}
Ok(())
})
}
}
impl Alarm for $name {
#[doc = $int_name]
fn clear_interrupt(&mut self) {
unsafe {
let timer = &(*pac::TIMER::ptr());
crate::atomic_register_access::write_bitmask_clear(
timer.intf().as_ptr(),
$armed_bit_mask,
);
timer
.intr()
.write_with_zero(|w| w.$int_alarm().clear_bit_by_one());
}
}
#[doc = $int_name]
fn enable_interrupt(&mut self) {
unsafe {
let timer = &(*pac::TIMER::ptr());
let reg = (&timer.inte()).as_ptr();
write_bitmask_set(reg, $armed_bit_mask);
}
}
fn disable_interrupt(&mut self) {
unsafe {
let timer = &(*pac::TIMER::ptr());
let reg = (&timer.inte()).as_ptr();
write_bitmask_clear(reg, $armed_bit_mask);
}
}
#[doc = $int_name]
fn schedule(&mut self, countdown: MicrosDurationU32) -> Result<(), ScheduleAlarmError> {
let timestamp = self.0.get_counter() + countdown;
self.schedule_internal(timestamp)
}
#[doc = $int_name]
fn schedule_at(&mut self, timestamp: Instant) -> Result<(), ScheduleAlarmError> {
let now = self.0.get_counter();
let duration = timestamp.ticks().saturating_sub(now.ticks());
if duration > u32::MAX.into() {
return Err(ScheduleAlarmError::AlarmTooLate);
}
self.schedule_internal(timestamp)
}
fn finished(&self) -> bool {
let bits: u32 = unsafe { &*TIMER::ptr() }.armed().read().bits();
(bits & $armed_bit_mask) == 0
}
fn cancel(&mut self) -> Result<(), ScheduleAlarmError> {
unsafe {
let timer = &*TIMER::ptr();
timer.armed().write_with_zero(|w| w.bits($armed_bit_mask));
crate::atomic_register_access::write_bitmask_clear(
timer.intf().as_ptr(),
$armed_bit_mask,
);
}
Ok(())
}
}
impl Sealed for $name {}
impl Drop for $name {
fn drop(&mut self) {
self.disable_interrupt();
release_alarm($armed_bit_mask)
}
}
};
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum ScheduleAlarmError {
AlarmTooLate,
}
impl_alarm!(Alarm0 {
rb: alarm0,
int: alarm_0,
int_name: "TIMER_IRQ_0",
armed_bit_mask: 0b0001
});
impl_alarm!(Alarm1 {
rb: alarm1,
int: alarm_1,
int_name: "TIMER_IRQ_1",
armed_bit_mask: 0b0010
});
impl_alarm!(Alarm2 {
rb: alarm2,
int: alarm_2,
int_name: "TIMER_IRQ_2",
armed_bit_mask: 0b0100
});
impl_alarm!(Alarm3 {
rb: alarm3,
int: alarm_3,
int_name: "TIMER_IRQ_3",
armed_bit_mask: 0b1000
});
#[cfg(feature = "rtic-monotonic")]
pub mod monotonic {
use super::{Alarm, Instant, Timer};
use fugit::ExtU32;
pub struct Monotonic<A>(pub Timer, A);
impl<A: Alarm> Monotonic<A> {
pub const fn new(timer: Timer, alarm: A) -> Self {
Self(timer, alarm)
}
}
impl<A: Alarm> rtic_monotonic::Monotonic for Monotonic<A> {
type Instant = Instant;
type Duration = fugit::MicrosDurationU64;
const DISABLE_INTERRUPT_ON_EMPTY_QUEUE: bool = false;
fn now(&mut self) -> Instant {
self.0.get_counter()
}
fn set_compare(&mut self, instant: Instant) {
let max_instant = self.0.get_counter() + 0xFFFF_FFFE.micros();
let wake_at = core::cmp::min(instant, max_instant);
let _ = self.1.schedule_at(wake_at);
self.1.enable_interrupt();
}
fn clear_compare_flag(&mut self) {
self.1.clear_interrupt();
}
fn zero() -> Self::Instant {
Instant::from_ticks(0)
}
unsafe fn reset(&mut self) {}
}
}