atsamd_hal/peripherals/timer/
d11.rs1use atsamd_hal_macros::hal_cfg;
3
4use crate::pac::Pm;
5#[hal_cfg("tc1-d11")]
6use crate::pac::{tc1::Count16 as Count16Reg, Tc1};
7#[hal_cfg("tc3-d21")]
8use crate::pac::{tc3::Count16 as Count16Reg, Tc3, Tc4, Tc5};
9
10use crate::clock;
11use crate::time::Hertz;
12
13mod common;
14pub use common::Count16;
15
16#[cfg(feature = "async")]
17mod async_api;
18
19#[cfg(feature = "async")]
20pub use async_api::*;
21
22pub struct TimerCounter<TC> {
38 freq: Hertz,
39 tc: TC,
40}
41impl<TC> TimerCounter<TC>
42where
43 TC: Count16,
44{
45 fn start_timer(&mut self, divider: u16, cycles: u16) {
47 self.disable();
49
50 let count = self.tc.count_16();
51
52 count.ctrla().write(|w| w.swrst().set_bit());
55 while count.status().read().syncbusy().bit_is_set() {}
56 while count.ctrla().read().bits() & 1 != 0 {}
59
60 count.ctrlbset().write(|w| {
61 w.dir().clear_bit();
63 w.oneshot().clear_bit()
65 });
66
67 count.cc(0).write(|w| unsafe { w.cc().bits(cycles) });
69
70 count.ctrla().modify(|_, w| {
71 match divider {
72 1 => w.prescaler().div1(),
73 2 => w.prescaler().div2(),
74 4 => w.prescaler().div4(),
75 8 => w.prescaler().div8(),
76 16 => w.prescaler().div16(),
77 64 => w.prescaler().div64(),
78 256 => w.prescaler().div256(),
79 1024 => w.prescaler().div1024(),
80 _ => unreachable!(),
81 };
82 w.wavegen().mfrq();
84 w.enable().set_bit();
85 w.runstdby().set_bit()
86 });
87 }
88
89 fn disable(&mut self) {
91 let count = self.tc.count_16();
92
93 count.ctrla().modify(|_, w| w.enable().clear_bit());
94 while count.status().read().syncbusy().bit_is_set() {}
95 }
96}
97
98macro_rules! tc {
99 ($($TYPE:ident: ($TC:ident, $pm:ident, $clock:ident),)+) => {
100 $(
101pub type $TYPE = TimerCounter<$TC>;
102
103impl Count16 for $TC {
104 fn count_16(&self) -> &Count16Reg {
105 self.count16()
106 }
107}
108
109impl TimerCounter<$TC>
110{
111 pub fn $pm(clock: &clock::$clock, tc: $TC, pm: &mut Pm) -> Self {
118 pm.apbcmask().modify(|_, w| w.$pm().set_bit());
120 {
121 let count = tc.count_16();
122
123 count.ctrla().modify(|_, w| w.enable().clear_bit());
125 while count.status().read().syncbusy().bit_is_set() {}
126 }
127 Self {
128 freq: clock.freq(),
129 tc,
130 }
131 }
132}
133 )+
134 }
135}
136
137#[hal_cfg("tc1-d11")]
139tc! {
140 TimerCounter1: (Tc1, tc1_, Tc1Tc2Clock),
141}
142#[hal_cfg("tc3-d21")]
144tc! {
145 TimerCounter3: (Tc3, tc3_, Tcc2Tc3Clock),
146 TimerCounter4: (Tc4, tc4_, Tc4Tc5Clock),
147 TimerCounter5: (Tc5, tc5_, Tc4Tc5Clock),
148}