stm32f1_hal/common/timer/
fix_timer.rs

1use super::*;
2
3/// Timer wrapper for fixed precision timers.
4///
5/// Uses `fugit::TimerDurationU32` for most of operations
6pub struct FTimer<TIM, const FREQ: u32> {
7    pub(crate) tim: TIM,
8    clk: HertzU32,
9}
10
11/// `FTimer` with precision of 1 μs (1 MHz sampling)
12pub type FTimerUs<TIM> = FTimer<TIM, 1_000_000>;
13
14/// `FTimer` with precision of 1 ms (1 kHz sampling)
15///
16/// NOTE: don't use this if your system frequency more than 65 MHz
17pub type FTimerMs<TIM> = FTimer<TIM, 1_000>;
18
19impl<TIM: GeneralTimer, const FREQ: u32> FTimer<TIM, FREQ> {
20    /// Initialize timer
21    pub fn new(tim: TIM, clk: HertzU32) -> Self {
22        let mut t = Self { tim, clk };
23        t.configure();
24        t
25    }
26
27    /// Calculate prescaler depending on `Clocks` state
28    pub fn configure(&mut self) {
29        assert!(self.clk.raw() % FREQ == 0);
30        let psc = self.clk.raw() / FREQ;
31        self.tim.set_prescaler(u16::try_from(psc - 1).unwrap());
32    }
33
34    pub fn counter(self) -> Counter<TIM, FREQ> {
35        Counter(self)
36    }
37
38    /// Releases the TIM peripheral
39    pub fn release(self) -> TIM {
40        self.tim
41    }
42
43    /// Starts listening for an `event`
44    ///
45    /// Note, you will also have to enable the TIM2 interrupt in the NVIC to start
46    /// receiving events.
47    pub fn listen(&mut self, event: Event) {
48        self.tim.listen_interrupt(event, true);
49    }
50
51    /// Clears interrupt associated with `event`.
52    ///
53    /// If the interrupt is not cleared, it will immediately retrigger after
54    /// the ISR has finished.
55    pub fn clear_interrupt(&mut self, event: Event) {
56        self.tim.clear_interrupt_flag(event);
57    }
58
59    pub fn get_interrupt(&mut self) -> Event {
60        self.tim.get_interrupt_flag()
61    }
62
63    /// Stops listening for an `event`
64    pub fn unlisten(&mut self, event: Event) {
65        self.tim.listen_interrupt(event, false);
66    }
67
68    /// Stopping timer in debug mode can cause troubles when sampling the signal
69    pub fn stop_in_debug(&mut self, state: bool) {
70        self.tim.stop_in_debug(state);
71    }
72}
73
74impl<TIM: MasterTimer, const FREQ: u32> FTimer<TIM, FREQ> {
75    pub fn set_master_mode(&mut self, mode: MasterMode) {
76        self.tim.master_mode(mode)
77    }
78}