use crate::Steal;
use crate::clocks::Clocks;
use pastey::paste;
pub struct Ticks {
ticks: rp2350_pac::TICKS,
cycles_per_tick: u16,
}
impl Ticks {
#[inline]
pub fn init(ticks: rp2350_pac::TICKS, clocks: &Clocks) -> Self {
let cycles_per_tick = clocks.ref_freq() / 1_000_000;
assert!(
(1..=0x1FF).contains(&cycles_per_tick),
"clk_ref of {} Hz is out of range for a 1µs tick",
clocks.ref_freq()
);
Self {
ticks,
cycles_per_tick: cycles_per_tick as u16,
}
}
#[inline]
pub unsafe fn steal() -> Steal<Self> {
Steal(Self {
ticks: unsafe { rp2350_pac::TICKS::steal() },
cycles_per_tick: 0,
})
}
#[inline]
pub fn cycles_per_tick(&self) -> u16 {
self.cycles_per_tick
}
#[inline]
pub unsafe fn regs(&self) -> &rp2350_pac::ticks::RegisterBlock {
&self.ticks
}
#[inline]
pub fn release(self) -> rp2350_pac::TICKS {
self.ticks
}
}
macro_rules! impl_tick_gen {
($($name:ident => $prefix:ident),+ $(,)?) => {
paste! {
$(
impl Ticks {
#[doc = concat!("Enable the ", stringify!($name), " tick generator.")]
#[inline]
pub fn [<enable_ $name>](&mut self) {
self.ticks.[<$prefix _ctrl>].set_enable();
}
#[doc = concat!("Disable the ", stringify!($name), " tick generator.")]
#[inline]
pub fn [<disable_ $name>](&mut self) {
self.ticks.[<$prefix _ctrl>].clr_enable();
}
#[doc = concat!("Check if the ", stringify!($name), " tick generator is running.")]
#[inline]
pub fn [<$name _running>](&self) -> bool {
self.ticks.[<$prefix _ctrl>].running()
}
#[doc = concat!("Check if the ", stringify!($name), " tick generator is enabled.")]
#[inline]
pub fn [<$name _enabled>](&self) -> bool {
self.ticks.[<$prefix _ctrl>].enable()
}
#[doc = concat!("Set the ", stringify!($name), " cycles per tick (9-bit, max 511).")]
#[inline]
pub fn [<set_ $name _cycles>](&mut self, cycles: u16) {
assert!(cycles <= 0x1FF, "cycles per tick must fit in 9 bits");
self.ticks.[<$prefix _cycles>].[<write_ $prefix _cycles>](cycles as u32);
}
#[doc = concat!("Get the ", stringify!($name), " cycles per tick.")]
#[inline]
pub fn [<$name _cycles>](&self) -> u16 {
self.ticks.[<$prefix _cycles>].[<$prefix _cycles>]() as u16
}
#[doc = concat!("Get the ", stringify!($name), " tick count.")]
#[inline]
pub fn [<$name _count>](&self) -> u16 {
self.ticks.[<$prefix _count>].[<$prefix _count>]() as u16
}
#[doc = concat!("Initialize the ", stringify!($name), " tick generator (disable, set cycles, enable).")]
#[inline]
pub fn [<init_ $name>](&mut self) {
assert!(self.cycles_per_tick > 0, "no tick rate configured (was this handle stolen?)");
self.[<disable_ $name>]();
self.[<set_ $name _cycles>](self.cycles_per_tick);
self.[<enable_ $name>]();
}
}
)+
}
};
}
impl_tick_gen!(
proc0 => proc0,
proc1 => proc1,
timer0 => timer0,
timer1 => timer1,
watchdog => watchdog,
riscv => riscv,
);