use atsamd_hal_macros::hal_cfg;
use crate::pac::Pm;
#[hal_cfg("tc1-d11")]
use crate::pac::{tc1::Count16 as Count16Reg, Tc1};
#[hal_cfg("tc3-d21")]
use crate::pac::{tc3::Count16 as Count16Reg, Tc3, Tc4, Tc5};
use crate::clock;
use crate::time::Hertz;
mod common;
pub use common::Count16;
#[cfg(feature = "async")]
mod async_api;
#[cfg(feature = "async")]
pub use async_api::*;
pub struct TimerCounter<TC> {
freq: Hertz,
tc: TC,
}
impl<TC> TimerCounter<TC>
where
TC: Count16,
{
fn start_timer(&mut self, divider: u16, cycles: u16) {
self.disable();
let count = self.tc.count_16();
count.ctrla().write(|w| w.swrst().set_bit());
while count.status().read().syncbusy().bit_is_set() {}
while count.ctrla().read().bits() & 1 != 0 {}
count.ctrlbset().write(|w| {
w.dir().clear_bit();
w.oneshot().clear_bit()
});
count.cc(0).write(|w| unsafe { w.cc().bits(cycles) });
count.ctrla().modify(|_, w| {
match divider {
1 => w.prescaler().div1(),
2 => w.prescaler().div2(),
4 => w.prescaler().div4(),
8 => w.prescaler().div8(),
16 => w.prescaler().div16(),
64 => w.prescaler().div64(),
256 => w.prescaler().div256(),
1024 => w.prescaler().div1024(),
_ => unreachable!(),
};
w.wavegen().mfrq();
w.enable().set_bit();
w.runstdby().set_bit()
});
}
fn disable(&mut self) {
let count = self.tc.count_16();
count.ctrla().modify(|_, w| w.enable().clear_bit());
while count.status().read().syncbusy().bit_is_set() {}
}
}
macro_rules! tc {
($($TYPE:ident: ($TC:ident, $pm:ident, $clock:ident),)+) => {
$(
pub type $TYPE = TimerCounter<$TC>;
impl Count16 for $TC {
fn count_16(&self) -> &Count16Reg {
self.count16()
}
}
impl TimerCounter<$TC>
{
pub fn $pm(clock: &clock::$clock, tc: $TC, pm: &mut Pm) -> Self {
pm.apbcmask().modify(|_, w| w.$pm().set_bit());
{
let count = tc.count_16();
count.ctrla().modify(|_, w| w.enable().clear_bit());
while count.status().read().syncbusy().bit_is_set() {}
}
Self {
freq: clock.freq(),
tc,
}
}
}
)+
}
}
#[hal_cfg("tc1-d11")]
tc! {
TimerCounter1: (Tc1, tc1_, Tc1Tc2Clock),
}
#[hal_cfg("tc3-d21")]
tc! {
TimerCounter3: (Tc3, tc3_, Tcc2Tc3Clock),
TimerCounter4: (Tc4, tc4_, Tc4Tc5Clock),
TimerCounter5: (Tc5, tc5_, Tc4Tc5Clock),
}