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: Hertz,
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: Hertz) -> 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    /// Creates `Counter` that imlements [embedded_hal_02::timer::CountDown]
35    pub fn counter(self) -> Counter<TIM, FREQ> {
36        Counter(self)
37    }
38
39    /// Creates `Delay` that imlements [embedded_hal_02::blocking::delay] traits
40    pub fn delay(self) -> Delay<TIM, FREQ> {
41        Delay(self)
42    }
43
44    /// Releases the TIM peripheral
45    pub fn release(self) -> TIM {
46        self.tim
47    }
48
49    /// Starts listening for an `event`
50    ///
51    /// Note, you will also have to enable the TIM2 interrupt in the NVIC to start
52    /// receiving events.
53    pub fn listen(&mut self, event: Event) {
54        self.tim.listen_interrupt(event, true);
55    }
56
57    /// Clears interrupt associated with `event`.
58    ///
59    /// If the interrupt is not cleared, it will immediately retrigger after
60    /// the ISR has finished.
61    pub fn clear_interrupt(&mut self, event: Event) {
62        self.tim.clear_interrupt_flag(event);
63    }
64
65    pub fn get_interrupt(&mut self) -> Event {
66        self.tim.get_interrupt_flag()
67    }
68
69    /// Stops listening for an `event`
70    pub fn unlisten(&mut self, event: Event) {
71        self.tim.listen_interrupt(event, false);
72    }
73
74    /// Stopping timer in debug mode can cause troubles when sampling the signal
75    pub fn stop_in_debug(&mut self, state: bool) {
76        self.tim.stop_in_debug(state);
77    }
78}
79
80impl<TIM: MasterTimer, const FREQ: u32> FTimer<TIM, FREQ> {
81    pub fn set_master_mode(&mut self, mode: MasterMode) {
82        self.tim.master_mode(mode)
83    }
84}