stm32f7xx_hal/timer/
counter.rs

1use super::{compute_arr_presc, Error, Event, FTimer, Instance, SysEvent, Timer};
2use crate::pac::SYST;
3use core::ops::{Deref, DerefMut};
4use fugit::{HertzU32 as Hertz, TimerDurationU32, TimerInstantU32};
5
6/// Hardware timers
7pub struct CounterHz<TIM>(pub(super) Timer<TIM>);
8
9impl<T> Deref for CounterHz<T> {
10    type Target = Timer<T>;
11    fn deref(&self) -> &Self::Target {
12        &self.0
13    }
14}
15
16impl<T> DerefMut for CounterHz<T> {
17    fn deref_mut(&mut self) -> &mut Self::Target {
18        &mut self.0
19    }
20}
21
22impl<TIM: Instance> CounterHz<TIM> {
23    /// Releases the TIM peripheral
24    pub fn release(mut self) -> Timer<TIM> {
25        // stop timer
26        self.tim.cr1_reset();
27        self.0
28    }
29}
30
31impl<TIM: Instance> CounterHz<TIM> {
32    pub fn start(&mut self, timeout: Hertz) -> Result<(), Error> {
33        // pause
34        self.tim.disable_counter();
35        // reset counter
36        self.tim.reset_counter();
37
38        let (psc, arr) = compute_arr_presc(timeout.raw(), self.clk.raw());
39        self.tim.set_prescaler(psc);
40        self.tim.set_auto_reload(arr)?;
41
42        // Trigger update event to load the registers
43        self.tim.trigger_update();
44
45        // start counter
46        self.tim.enable_counter();
47
48        Ok(())
49    }
50
51    pub fn wait(&mut self) -> nb::Result<(), Error> {
52        if self.tim.get_interrupt_flag().contains(Event::Update) {
53            self.tim.clear_interrupt_flag(Event::Update);
54            Ok(())
55        } else {
56            Err(nb::Error::WouldBlock)
57        }
58    }
59
60    pub fn cancel(&mut self) -> Result<(), Error> {
61        if !self.tim.is_counter_enabled() {
62            return Err(Error::Disabled);
63        }
64
65        // disable counter
66        self.tim.disable_counter();
67        Ok(())
68    }
69}
70
71/// Periodic non-blocking timer that imlements [embedded_hal::timer::CountDown]
72pub struct Counter<TIM, const FREQ: u32>(pub(super) FTimer<TIM, FREQ>);
73
74impl<T, const FREQ: u32> Deref for Counter<T, FREQ> {
75    type Target = FTimer<T, FREQ>;
76    fn deref(&self) -> &Self::Target {
77        &self.0
78    }
79}
80
81impl<T, const FREQ: u32> DerefMut for Counter<T, FREQ> {
82    fn deref_mut(&mut self) -> &mut Self::Target {
83        &mut self.0
84    }
85}
86
87/// `Counter` with precision of 1 μs (1 MHz sampling)
88pub type CounterUs<TIM> = Counter<TIM, 1_000_000>;
89
90/// `Counter` with precision of of 1 ms (1 kHz sampling)
91///
92/// NOTE: don't use this if your system frequency more than 65 MHz
93pub type CounterMs<TIM> = Counter<TIM, 1_000>;
94
95impl<TIM: Instance, const FREQ: u32> Counter<TIM, FREQ> {
96    /// Releases the TIM peripheral
97    pub fn release(mut self) -> FTimer<TIM, FREQ> {
98        // stop counter
99        self.tim.cr1_reset();
100        self.0
101    }
102
103    pub fn now(&self) -> TimerInstantU32<FREQ> {
104        TimerInstantU32::from_ticks(self.tim.read_count().into())
105    }
106
107    pub fn start(&mut self, timeout: TimerDurationU32<FREQ>) -> Result<(), Error> {
108        // pause
109        self.tim.disable_counter();
110        // reset counter
111        self.tim.reset_counter();
112
113        self.tim.set_auto_reload(timeout.ticks() - 1)?;
114
115        // Trigger update event to load the registers
116        self.tim.trigger_update();
117
118        // start counter
119        self.tim.enable_counter();
120
121        Ok(())
122    }
123
124    pub fn wait(&mut self) -> nb::Result<(), Error> {
125        if self.tim.get_interrupt_flag().contains(Event::Update) {
126            self.tim.clear_interrupt_flag(Event::Update);
127            Ok(())
128        } else {
129            Err(nb::Error::WouldBlock)
130        }
131    }
132
133    pub fn cancel(&mut self) -> Result<(), Error> {
134        if !self.tim.is_counter_enabled() {
135            return Err(Error::Disabled);
136        }
137
138        // disable counter
139        self.tim.disable_counter();
140        Ok(())
141    }
142}
143
144impl<TIM: Instance, const FREQ: u32> fugit_timer::Timer<FREQ> for Counter<TIM, FREQ> {
145    type Error = Error;
146
147    fn now(&mut self) -> TimerInstantU32<FREQ> {
148        Self::now(self)
149    }
150
151    fn start(&mut self, duration: TimerDurationU32<FREQ>) -> Result<(), Self::Error> {
152        self.start(duration)
153    }
154
155    fn cancel(&mut self) -> Result<(), Self::Error> {
156        self.cancel()
157    }
158
159    fn wait(&mut self) -> nb::Result<(), Self::Error> {
160        self.wait()
161    }
162}
163
164impl Timer<SYST> {
165    /// Creates [SysCounterHz] which takes [Hertz] as Duration
166    pub fn counter_hz(self) -> SysCounterHz {
167        SysCounterHz(self)
168    }
169
170    /// Creates [SysCounter] with custom precision (core frequency recommended is known)
171    pub fn counter<const FREQ: u32>(self) -> SysCounter<FREQ> {
172        SysCounter(self)
173    }
174
175    /// Creates [SysCounter] 1 microsecond precision
176    pub fn counter_us(self) -> SysCounterUs {
177        SysCounter(self)
178    }
179}
180
181/// Hardware timers
182pub struct SysCounterHz(Timer<SYST>);
183
184impl Deref for SysCounterHz {
185    type Target = Timer<SYST>;
186    fn deref(&self) -> &Self::Target {
187        &self.0
188    }
189}
190
191impl DerefMut for SysCounterHz {
192    fn deref_mut(&mut self) -> &mut Self::Target {
193        &mut self.0
194    }
195}
196
197impl SysCounterHz {
198    pub fn start(&mut self, timeout: Hertz) -> Result<(), Error> {
199        let rvr = self.clk.raw() / timeout.raw() - 1;
200
201        if rvr >= (1 << 24) {
202            return Err(Error::WrongAutoReload);
203        }
204
205        self.tim.set_reload(rvr);
206        self.tim.clear_current();
207        self.tim.enable_counter();
208
209        Ok(())
210    }
211
212    pub fn wait(&mut self) -> nb::Result<(), Error> {
213        if self.tim.has_wrapped() {
214            Ok(())
215        } else {
216            Err(nb::Error::WouldBlock)
217        }
218    }
219
220    pub fn cancel(&mut self) -> Result<(), Error> {
221        if !self.tim.is_counter_enabled() {
222            return Err(Error::Disabled);
223        }
224
225        self.tim.disable_counter();
226        Ok(())
227    }
228}
229
230pub type SysCounterUs = SysCounter<1_000_000>;
231
232/// SysTick timer with precision of 1 μs (1 MHz sampling)
233pub struct SysCounter<const FREQ: u32>(Timer<SYST>);
234
235impl<const FREQ: u32> Deref for SysCounter<FREQ> {
236    type Target = Timer<SYST>;
237    fn deref(&self) -> &Self::Target {
238        &self.0
239    }
240}
241
242impl<const FREQ: u32> DerefMut for SysCounter<FREQ> {
243    fn deref_mut(&mut self) -> &mut Self::Target {
244        &mut self.0
245    }
246}
247
248impl<const FREQ: u32> SysCounter<FREQ> {
249    /// Starts listening for an `event`
250    pub fn listen(&mut self, event: SysEvent) {
251        match event {
252            SysEvent::Update => self.tim.enable_interrupt(),
253        }
254    }
255
256    /// Stops listening for an `event`
257    pub fn unlisten(&mut self, event: SysEvent) {
258        match event {
259            SysEvent::Update => self.tim.disable_interrupt(),
260        }
261    }
262
263    pub fn now(&self) -> TimerInstantU32<FREQ> {
264        TimerInstantU32::from_ticks(
265            (SYST::get_reload() - SYST::get_current()) / (self.clk.raw() / FREQ),
266        )
267    }
268
269    pub fn start(&mut self, timeout: TimerDurationU32<FREQ>) -> Result<(), Error> {
270        let rvr = timeout.ticks() * (self.clk.raw() / FREQ) - 1;
271
272        if rvr >= (1 << 24) {
273            return Err(Error::WrongAutoReload);
274        }
275
276        self.tim.set_reload(rvr);
277        self.tim.clear_current();
278        self.tim.enable_counter();
279
280        Ok(())
281    }
282
283    pub fn wait(&mut self) -> nb::Result<(), Error> {
284        if self.tim.has_wrapped() {
285            Ok(())
286        } else {
287            Err(nb::Error::WouldBlock)
288        }
289    }
290
291    pub fn cancel(&mut self) -> Result<(), Error> {
292        if !self.tim.is_counter_enabled() {
293            return Err(Error::Disabled);
294        }
295
296        self.tim.disable_counter();
297        Ok(())
298    }
299}
300
301impl<const FREQ: u32> fugit_timer::Timer<FREQ> for SysCounter<FREQ> {
302    type Error = Error;
303
304    fn now(&mut self) -> TimerInstantU32<FREQ> {
305        Self::now(self)
306    }
307
308    fn start(&mut self, duration: TimerDurationU32<FREQ>) -> Result<(), Self::Error> {
309        self.start(duration)
310    }
311
312    fn wait(&mut self) -> nb::Result<(), Self::Error> {
313        self.wait()
314    }
315
316    fn cancel(&mut self) -> Result<(), Self::Error> {
317        self.cancel()
318    }
319}