stm32f1xx_hal/
timer.rs

1/*!
2  # Timer
3
4  ## Alternate function remapping
5
6  This is a list of the remap settings you can use to assign pins to PWM channels
7  and the QEI peripherals
8
9  ### TIM1
10
11  Not available on STM32F101.
12
13  | Channel | Tim1NoRemap | Tim1FullRemap |
14  |:---:|:-----------:|:-------------:|
15  | CH1 |     PA8     |       PE9     |
16  | CH2 |     PA9     |       PE11    |
17  | CH3 |     PA10    |       PE13    |
18  | CH4 |     PA11    |       PE14    |
19
20  ### TIM2
21
22  | Channel | Tim2NoRemap | Tim2PartialRemap1 | Tim2PartialRemap2 | Tim2FullRemap |
23  |:---:|:-----------:|:-----------------:|:-----------------:|:-------------:|
24  | CH1 |     PA0     |        PA15       |        PA0        |      PA15     |
25  | CH2 |     PA1     |        PB3        |        PA1        |      PB3      |
26  | CH3 |     PA2     |        PA2        |        PB10       |      PB10     |
27  | CH4 |     PA3     |        PA3        |        PB11       |      PB11     |
28
29  ### TIM3
30
31  | Channel | Tim3NoRemap | Tim3PartialRemap | Tim3FullRemap |
32  |:---:|:-----------:|:----------------:|:-------------:|
33  | CH1 |     PA6     |        PB4       |      PC6      |
34  | CH2 |     PA7     |        PB5       |      PC7      |
35  | CH3 |     PB0     |        PB0       |      PC8      |
36  | CH4 |     PB1     |        PB1       |      PC9      |
37
38  ### TIM4
39
40  Not available on low density devices.
41
42  | Channel | Tim4NoRemap | Tim4Remap |
43  |:---:|:-----------:|:---------:|
44  | CH1 |     PB6     |    PD12   |
45  | CH2 |     PB7     |    PD13   |
46  | CH3 |     PB8     |    PD14   |
47  | CH4 |     PB9     |    PD15   |
48*/
49#![allow(non_upper_case_globals)]
50
51use crate::bb;
52use crate::pac::{self, DBGMCU as DBG, RCC};
53
54use crate::rcc::{self, Clocks};
55use core::convert::TryFrom;
56use cortex_m::peripheral::syst::SystClkSource;
57use cortex_m::peripheral::SYST;
58
59use crate::time::Hertz;
60
61#[cfg(feature = "rtic")]
62pub mod monotonic;
63#[cfg(feature = "rtic")]
64pub use monotonic::*;
65pub mod pwm_input;
66pub use pwm_input::*;
67pub(crate) mod pins;
68pub use pins::*;
69pub mod delay;
70pub use delay::*;
71pub mod counter;
72pub use counter::*;
73pub mod pwm;
74pub use pwm::*;
75
76mod hal_02;
77
78/// Timer wrapper
79pub struct Timer<TIM> {
80    pub(crate) tim: TIM,
81    pub(crate) clk: Hertz,
82}
83
84#[derive(Clone, Copy, PartialEq, Eq)]
85#[repr(u8)]
86pub enum Channel {
87    C1 = 0,
88    C2 = 1,
89    C3 = 2,
90    C4 = 3,
91}
92
93/// Interrupt events
94#[derive(Clone, Copy, PartialEq, Eq)]
95pub enum SysEvent {
96    /// [Timer] timed out / count down ended
97    Update,
98}
99
100bitflags::bitflags! {
101    pub struct Event: u32 {
102        const Update  = 1 << 0;
103        const C1 = 1 << 1;
104        const C2 = 1 << 2;
105        const C3 = 1 << 3;
106        const C4 = 1 << 4;
107    }
108}
109
110#[derive(Debug, Eq, PartialEq, Copy, Clone)]
111pub enum Error {
112    /// Timer is disabled
113    Disabled,
114    WrongAutoReload,
115}
116
117pub trait TimerExt: Sized {
118    /// Non-blocking [Counter] with custom fixed precision
119    fn counter<const FREQ: u32>(self, clocks: &Clocks) -> Counter<Self, FREQ>;
120    /// Non-blocking [Counter] with fixed precision of 1 ms (1 kHz sampling)
121    ///
122    /// Can wait from 2 ms to 65 sec for 16-bit timer and from 2 ms to 49 days for 32-bit timer.
123    ///
124    /// NOTE: don't use this if your system frequency more than 65 MHz
125    fn counter_ms(self, clocks: &Clocks) -> CounterMs<Self> {
126        self.counter::<1_000>(clocks)
127    }
128    /// Non-blocking [Counter] with fixed precision of 1 μs (1 MHz sampling)
129    ///
130    /// Can wait from 2 μs to 65 ms for 16-bit timer and from 2 μs to 71 min for 32-bit timer.
131    fn counter_us(self, clocks: &Clocks) -> CounterUs<Self> {
132        self.counter::<1_000_000>(clocks)
133    }
134    /// Non-blocking [Counter] with dynamic precision which uses `Hertz` as Duration units
135    fn counter_hz(self, clocks: &Clocks) -> CounterHz<Self>;
136
137    /// Blocking [Delay] with custom fixed precision
138    fn delay<const FREQ: u32>(self, clocks: &Clocks) -> Delay<Self, FREQ>;
139    /// Blocking [Delay] with fixed precision of 1 ms (1 kHz sampling)
140    ///
141    /// Can wait from 2 ms to 49 days.
142    ///
143    /// NOTE: don't use this if your system frequency more than 65 MHz
144    fn delay_ms(self, clocks: &Clocks) -> DelayMs<Self> {
145        self.delay::<1_000>(clocks)
146    }
147    /// Blocking [Delay] with fixed precision of 1 μs (1 MHz sampling)
148    ///
149    /// Can wait from 2 μs to 71 min.
150    fn delay_us(self, clocks: &Clocks) -> DelayUs<Self> {
151        self.delay::<1_000_000>(clocks)
152    }
153}
154
155impl<TIM: Instance> TimerExt for TIM {
156    fn counter<const FREQ: u32>(self, clocks: &Clocks) -> Counter<Self, FREQ> {
157        FTimer::new(self, clocks).counter()
158    }
159    fn counter_hz(self, clocks: &Clocks) -> CounterHz<Self> {
160        Timer::new(self, clocks).counter_hz()
161    }
162    fn delay<const FREQ: u32>(self, clocks: &Clocks) -> Delay<Self, FREQ> {
163        FTimer::new(self, clocks).delay()
164    }
165}
166
167pub trait SysTimerExt: Sized {
168    /// Creates timer which takes [Hertz] as Duration
169    fn counter_hz(self, clocks: &Clocks) -> SysCounterHz;
170
171    /// Creates timer with custom precision (core frequency recommended is known)
172    fn counter<const FREQ: u32>(self, clocks: &Clocks) -> SysCounter<FREQ>;
173    /// Creates timer with precision of 1 μs (1 MHz sampling)
174    fn counter_us(self, clocks: &Clocks) -> SysCounterUs {
175        self.counter::<1_000_000>(clocks)
176    }
177    /// Blocking [Delay] with custom precision
178    fn delay(self, clocks: &Clocks) -> SysDelay;
179}
180
181impl SysTimerExt for SYST {
182    fn counter_hz(self, clocks: &Clocks) -> SysCounterHz {
183        Timer::syst(self, clocks).counter_hz()
184    }
185    fn counter<const FREQ: u32>(self, clocks: &Clocks) -> SysCounter<FREQ> {
186        Timer::syst(self, clocks).counter()
187    }
188    fn delay(self, clocks: &Clocks) -> SysDelay {
189        Timer::syst_external(self, clocks).delay()
190    }
191}
192
193impl Timer<SYST> {
194    /// Initialize SysTick timer
195    pub fn syst(mut tim: SYST, clocks: &Clocks) -> Self {
196        tim.set_clock_source(SystClkSource::Core);
197        Self {
198            tim,
199            clk: clocks.hclk(),
200        }
201    }
202
203    /// Initialize SysTick timer and set it frequency to `HCLK / 8`
204    pub fn syst_external(mut tim: SYST, clocks: &Clocks) -> Self {
205        tim.set_clock_source(SystClkSource::External);
206        Self {
207            tim,
208            clk: clocks.hclk() / 8,
209        }
210    }
211
212    pub fn configure(&mut self, clocks: &Clocks) {
213        self.tim.set_clock_source(SystClkSource::Core);
214        self.clk = clocks.hclk();
215    }
216
217    pub fn configure_external(&mut self, clocks: &Clocks) {
218        self.tim.set_clock_source(SystClkSource::External);
219        self.clk = clocks.hclk() / 8;
220    }
221
222    pub fn release(self) -> SYST {
223        self.tim
224    }
225
226    /// Starts listening for an `event`
227    pub fn listen(&mut self, event: SysEvent) {
228        match event {
229            SysEvent::Update => self.tim.enable_interrupt(),
230        }
231    }
232
233    /// Stops listening for an `event`
234    pub fn unlisten(&mut self, event: SysEvent) {
235        match event {
236            SysEvent::Update => self.tim.disable_interrupt(),
237        }
238    }
239
240    /// Resets the counter
241    pub fn reset(&mut self) {
242        // According to the Cortex-M3 Generic User Guide, the interrupt request is only generated
243        // when the counter goes from 1 to 0, so writing zero should not trigger an interrupt
244        self.tim.clear_current();
245    }
246}
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249#[repr(u8)]
250pub enum Ocm {
251    Frozen = 0,
252    ActiveOnMatch = 1,
253    InactiveOnMatch = 2,
254    Toggle = 3,
255    ForceInactive = 4,
256    ForceActive = 5,
257    PwmMode1 = 6,
258    PwmMode2 = 7,
259}
260
261mod sealed {
262    use super::{Channel, Event, Ocm, DBG};
263    pub trait General {
264        type Width: Into<u32> + From<u16>;
265        fn max_auto_reload() -> u32;
266        unsafe fn set_auto_reload_unchecked(&mut self, arr: u32);
267        fn set_auto_reload(&mut self, arr: u32) -> Result<(), super::Error>;
268        fn read_auto_reload() -> u32;
269        fn enable_preload(&mut self, b: bool);
270        fn enable_counter(&mut self);
271        fn disable_counter(&mut self);
272        fn is_counter_enabled(&self) -> bool;
273        fn reset_counter(&mut self);
274        fn set_prescaler(&mut self, psc: u16);
275        fn read_prescaler(&self) -> u16;
276        fn trigger_update(&mut self);
277        fn clear_interrupt_flag(&mut self, event: Event);
278        fn listen_interrupt(&mut self, event: Event, b: bool);
279        fn get_interrupt_flag(&self) -> Event;
280        fn read_count(&self) -> Self::Width;
281        fn start_one_pulse(&mut self);
282        fn cr1_reset(&mut self);
283        fn stop_in_debug(&mut self, dbg: &mut DBG, state: bool);
284    }
285
286    pub trait WithPwm: General {
287        const CH_NUMBER: u8;
288        fn read_cc_value(channel: u8) -> u32;
289        fn set_cc_value(channel: u8, value: u32);
290        fn preload_output_channel_in_mode(&mut self, channel: Channel, mode: Ocm);
291        fn start_pwm(&mut self);
292        fn enable_channel(channel: u8, b: bool);
293    }
294
295    pub trait MasterTimer: General {
296        type Mms;
297        fn master_mode(&mut self, mode: Self::Mms);
298    }
299}
300pub(crate) use sealed::{General, MasterTimer, WithPwm};
301
302pub trait Instance:
303    crate::Sealed + rcc::Enable + rcc::Reset + rcc::BusTimerClock + General
304{
305}
306
307macro_rules! hal {
308    ($($TIM:ty: [
309        $Timer:ident,
310        $bits:ty,
311        $dbg_timX_stop:ident,
312        $(c: ($cnum:ident $(, $aoe:ident)?),)?
313        $(m: $timbase:ident,)?
314    ],)+) => {
315        $(
316            impl Instance for $TIM { }
317            pub type $Timer = Timer<$TIM>;
318
319            impl General for $TIM {
320                type Width = $bits;
321
322                #[inline(always)]
323                fn max_auto_reload() -> u32 {
324                    <$bits>::MAX as u32
325                }
326                #[inline(always)]
327                unsafe fn set_auto_reload_unchecked(&mut self, arr: u32) {
328                    self.arr.write(|w| w.bits(arr))
329                }
330                #[inline(always)]
331                fn set_auto_reload(&mut self, arr: u32) -> Result<(), Error> {
332                    // Note: Make it impossible to set the ARR value to 0, since this
333                    // would cause an infinite loop.
334                    if arr > 0 && arr <= Self::max_auto_reload() {
335                        Ok(unsafe { self.set_auto_reload_unchecked(arr) })
336                    } else {
337                        Err(Error::WrongAutoReload)
338                    }
339                }
340                #[inline(always)]
341                fn read_auto_reload() -> u32 {
342                    let tim = unsafe { &*<$TIM>::ptr() };
343                    tim.arr.read().bits()
344                }
345                #[inline(always)]
346                fn enable_preload(&mut self, b: bool) {
347                    self.cr1.modify(|_, w| w.arpe().bit(b));
348                }
349                #[inline(always)]
350                fn enable_counter(&mut self) {
351                    self.cr1.modify(|_, w| w.cen().set_bit());
352                }
353                #[inline(always)]
354                fn disable_counter(&mut self) {
355                    self.cr1.modify(|_, w| w.cen().clear_bit());
356                }
357                #[inline(always)]
358                fn is_counter_enabled(&self) -> bool {
359                    self.cr1.read().cen().is_enabled()
360                }
361                #[inline(always)]
362                fn reset_counter(&mut self) {
363                    self.cnt.reset();
364                }
365                #[inline(always)]
366                fn set_prescaler(&mut self, psc: u16) {
367                    self.psc.write(|w| w.psc().bits(psc) );
368                }
369                #[inline(always)]
370                fn read_prescaler(&self) -> u16 {
371                    self.psc.read().psc().bits()
372                }
373                #[inline(always)]
374                fn trigger_update(&mut self) {
375                    // Sets the URS bit to prevent an interrupt from being triggered by
376                    // the UG bit
377                    self.cr1.modify(|_, w| w.urs().set_bit());
378                    self.egr.write(|w| w.ug().set_bit());
379                    self.cr1.modify(|_, w| w.urs().clear_bit());
380                }
381                #[inline(always)]
382                fn clear_interrupt_flag(&mut self, event: Event) {
383                    self.sr.write(|w| unsafe { w.bits(0xffff & !event.bits()) });
384                }
385                #[inline(always)]
386                fn listen_interrupt(&mut self, event: Event, b: bool) {
387                    if b {
388                        self.dier.modify(|r, w| unsafe { w.bits(r.bits() | event.bits()) });
389                    } else {
390                        self.dier.modify(|r, w| unsafe { w.bits(r.bits() & !event.bits()) });
391                    }
392                }
393                #[inline(always)]
394                fn get_interrupt_flag(&self) -> Event {
395                    Event::from_bits_truncate(self.sr.read().bits())
396                }
397                #[inline(always)]
398                fn read_count(&self) -> Self::Width {
399                    self.cnt.read().bits() as Self::Width
400                }
401                #[inline(always)]
402                fn start_one_pulse(&mut self) {
403                    self.cr1.write(|w| unsafe { w.bits(1 << 3) }.cen().set_bit());
404                }
405                #[inline(always)]
406                fn cr1_reset(&mut self) {
407                    self.cr1.reset();
408                }
409                #[inline(always)]
410                fn stop_in_debug(&mut self, dbg: &mut DBG, state: bool) {
411                    dbg.cr.modify(|_, w| w.$dbg_timX_stop().bit(state));
412                }
413            }
414            $(with_pwm!($TIM: $cnum $(, $aoe)?);)?
415
416            $(impl MasterTimer for $TIM {
417                type Mms = pac::$timbase::cr2::MMS_A;
418                fn master_mode(&mut self, mode: Self::Mms) {
419                    self.cr2.modify(|_,w| w.mms().variant(mode));
420                }
421            })?
422        )+
423    }
424}
425
426macro_rules! with_pwm {
427    ($TIM:ty: CH1) => {
428        impl WithPwm for $TIM {
429            const CH_NUMBER: u8 = 1;
430
431            #[inline(always)]
432            fn read_cc_value(channel: u8) -> u32 {
433                let tim = unsafe { &*<$TIM>::ptr() };
434                if channel < Self::CH_NUMBER {
435                    tim.ccr[channel as usize].read().bits()
436                } else {
437                    0
438                }
439            }
440
441            #[inline(always)]
442            fn set_cc_value(channel: u8, value: u32) {
443                let tim = unsafe { &*<$TIM>::ptr() };
444                #[allow(unused_unsafe)]
445                if channel < Self::CH_NUMBER {
446                    tim.ccr[channel as usize].write(|w| unsafe { w.bits(value) })
447                }
448            }
449
450            #[inline(always)]
451            fn preload_output_channel_in_mode(&mut self, channel: Channel, mode: Ocm) {
452                match channel {
453                    Channel::C1 => {
454                        self.ccmr1_output()
455                        .modify(|_, w| w.oc1pe().set_bit().oc1m().bits(mode as _) );
456                    }
457                    _ => {},
458                }
459            }
460
461            #[inline(always)]
462            fn start_pwm(&mut self) {
463                self.cr1.write(|w| w.cen().set_bit());
464            }
465
466            #[inline(always)]
467            fn enable_channel(c: u8, b: bool) {
468                let tim = unsafe { &*<$TIM>::ptr() };
469                if c < Self::CH_NUMBER {
470                    unsafe { bb::write(&tim.ccer, c*4, b); }
471                }
472            }
473        }
474    };
475    ($TIM:ty: CH2) => {
476        impl WithPwm for $TIM {
477            const CH_NUMBER: u8 = 2;
478
479            #[inline(always)]
480            fn read_cc_value(channel: u8) -> u32 {
481                let tim = unsafe { &*<$TIM>::ptr() };
482                if channel < Self::CH_NUMBER {
483                    tim.ccr[channel as usize].read().bits()
484                } else {
485                    0
486                }
487            }
488
489            #[inline(always)]
490            fn set_cc_value(channel: u8, value: u32) {
491                let tim = unsafe { &*<$TIM>::ptr() };
492                #[allow(unused_unsafe)]
493                if channel < Self::CH_NUMBER {
494                    tim.ccr[channel as usize].write(|w| unsafe { w.bits(value) })
495                }
496            }
497
498            #[inline(always)]
499            fn preload_output_channel_in_mode(&mut self, channel: Channel, mode: Ocm) {
500                match channel {
501                    Channel::C1 => {
502                        self.ccmr1_output()
503                        .modify(|_, w| w.oc1pe().set_bit().oc1m().bits(mode as _) );
504                    }
505                    Channel::C2 => {
506                        self.ccmr1_output()
507                        .modify(|_, w| w.oc2pe().set_bit().oc2m().bits(mode as _) );
508                    }
509                    _ => {},
510                }
511            }
512
513            #[inline(always)]
514            fn start_pwm(&mut self) {
515                self.cr1.write(|w| w.cen().set_bit());
516            }
517
518            #[inline(always)]
519            fn enable_channel(c: u8, b: bool) {
520                let tim = unsafe { &*<$TIM>::ptr() };
521                if c < Self::CH_NUMBER {
522                    unsafe { bb::write(&tim.ccer, c*4, b); }
523                }
524            }
525        }
526    };
527    ($TIM:ty: CH4 $(, $aoe:ident)?) => {
528        impl WithPwm for $TIM {
529            const CH_NUMBER: u8 = 4;
530
531            #[inline(always)]
532            fn read_cc_value(channel: u8) -> u32 {
533                let tim = unsafe { &*<$TIM>::ptr() };
534                tim.ccr[channel as usize].read().bits()
535            }
536
537            #[inline(always)]
538            fn set_cc_value(channel: u8, value: u32) {
539                let tim = unsafe { &*<$TIM>::ptr() };
540                tim.ccr[channel as usize].write(|w| unsafe { w.bits(value) })
541            }
542
543            #[inline(always)]
544            fn preload_output_channel_in_mode(&mut self, channel: Channel, mode: Ocm) {
545                match channel {
546                    Channel::C1 => {
547                        self.ccmr1_output()
548                        .modify(|_, w| w.oc1pe().set_bit().oc1m().bits(mode as _) );
549                    }
550                    Channel::C2 => {
551                        self.ccmr1_output()
552                        .modify(|_, w| w.oc2pe().set_bit().oc2m().bits(mode as _) );
553                    }
554                    Channel::C3 => {
555                        self.ccmr2_output()
556                        .modify(|_, w| w.oc3pe().set_bit().oc3m().bits(mode as _) );
557                    }
558                    Channel::C4 => {
559                        self.ccmr2_output()
560                        .modify(|_, w| w.oc4pe().set_bit().oc4m().bits(mode as _) );
561                    }
562                }
563            }
564
565            #[inline(always)]
566            fn start_pwm(&mut self) {
567                $(let $aoe = self.bdtr.modify(|_, w| w.aoe().set_bit());)?
568                self.cr1.write(|w| w.cen().set_bit());
569            }
570
571            #[inline(always)]
572            fn enable_channel(c: u8, b: bool) {
573                let tim = unsafe { &*<$TIM>::ptr() };
574                if c < Self::CH_NUMBER {
575                    unsafe { bb::write(&tim.ccer, c*4, b); }
576                }
577            }
578        }
579    }
580}
581
582impl<TIM: Instance> Timer<TIM> {
583    /// Initialize timer
584    pub fn new(tim: TIM, clocks: &Clocks) -> Self {
585        unsafe {
586            //NOTE(unsafe) this reference will only be used for atomic writes with no side effects
587            let rcc = &(*RCC::ptr());
588            // Enable and reset the timer peripheral
589            TIM::enable(rcc);
590            TIM::reset(rcc);
591        }
592
593        Self {
594            clk: TIM::timer_clock(clocks),
595            tim,
596        }
597    }
598
599    pub fn configure(&mut self, clocks: &Clocks) {
600        self.clk = TIM::timer_clock(clocks);
601    }
602
603    pub fn counter_hz(self) -> CounterHz<TIM> {
604        CounterHz(self)
605    }
606
607    pub fn release(self) -> TIM {
608        self.tim
609    }
610
611    /// Starts listening for an `event`
612    ///
613    /// Note, you will also have to enable the TIM2 interrupt in the NVIC to start
614    /// receiving events.
615    pub fn listen(&mut self, event: Event) {
616        self.tim.listen_interrupt(event, true);
617    }
618
619    /// Clears interrupt associated with `event`.
620    ///
621    /// If the interrupt is not cleared, it will immediately retrigger after
622    /// the ISR has finished.
623    pub fn clear_interrupt(&mut self, event: Event) {
624        self.tim.clear_interrupt_flag(event);
625    }
626
627    pub fn get_interrupt(&mut self) -> Event {
628        self.tim.get_interrupt_flag()
629    }
630
631    /// Stops listening for an `event`
632    pub fn unlisten(&mut self, event: Event) {
633        self.tim.listen_interrupt(event, false);
634    }
635
636    /// Stopping timer in debug mode can cause troubles when sampling the signal
637    pub fn stop_in_debug(&mut self, dbg: &mut DBG, state: bool) {
638        self.tim.stop_in_debug(dbg, state);
639    }
640}
641
642impl<TIM: Instance + MasterTimer> Timer<TIM> {
643    pub fn set_master_mode(&mut self, mode: TIM::Mms) {
644        self.tim.master_mode(mode)
645    }
646}
647
648/// Timer wrapper for fixed precision timers.
649///
650/// Uses `fugit::TimerDurationU32` for most of operations
651pub struct FTimer<TIM, const FREQ: u32> {
652    tim: TIM,
653}
654
655/// `FTimer` with precision of 1 μs (1 MHz sampling)
656pub type FTimerUs<TIM> = FTimer<TIM, 1_000_000>;
657
658/// `FTimer` with precision of 1 ms (1 kHz sampling)
659///
660/// NOTE: don't use this if your system frequency more than 65 MHz
661pub type FTimerMs<TIM> = FTimer<TIM, 1_000>;
662
663impl<TIM: Instance, const FREQ: u32> FTimer<TIM, FREQ> {
664    /// Initialize timer
665    pub fn new(tim: TIM, clocks: &Clocks) -> Self {
666        unsafe {
667            //NOTE(unsafe) this reference will only be used for atomic writes with no side effects
668            let rcc = &(*RCC::ptr());
669            // Enable and reset the timer peripheral
670            TIM::enable(rcc);
671            TIM::reset(rcc);
672        }
673
674        let mut t = Self { tim };
675        t.configure(clocks);
676        t
677    }
678
679    /// Calculate prescaler depending on `Clocks` state
680    pub fn configure(&mut self, clocks: &Clocks) {
681        let clk = TIM::timer_clock(clocks);
682        assert!(clk.raw() % FREQ == 0);
683        let psc = clk.raw() / FREQ;
684        self.tim.set_prescaler(u16::try_from(psc - 1).unwrap());
685    }
686
687    /// Creates `Counter` that imlements [embedded_hal::timer::CountDown]
688    pub fn counter(self) -> Counter<TIM, FREQ> {
689        Counter(self)
690    }
691
692    /// Creates `Delay` that imlements [embedded_hal::blocking::delay] traits
693    pub fn delay(self) -> Delay<TIM, FREQ> {
694        Delay(self)
695    }
696
697    /// Releases the TIM peripheral
698    pub fn release(self) -> TIM {
699        self.tim
700    }
701
702    /// Starts listening for an `event`
703    ///
704    /// Note, you will also have to enable the TIM2 interrupt in the NVIC to start
705    /// receiving events.
706    pub fn listen(&mut self, event: Event) {
707        self.tim.listen_interrupt(event, true);
708    }
709
710    /// Clears interrupt associated with `event`.
711    ///
712    /// If the interrupt is not cleared, it will immediately retrigger after
713    /// the ISR has finished.
714    pub fn clear_interrupt(&mut self, event: Event) {
715        self.tim.clear_interrupt_flag(event);
716    }
717
718    pub fn get_interrupt(&mut self) -> Event {
719        self.tim.get_interrupt_flag()
720    }
721
722    /// Stops listening for an `event`
723    pub fn unlisten(&mut self, event: Event) {
724        self.tim.listen_interrupt(event, false);
725    }
726
727    /// Stopping timer in debug mode can cause troubles when sampling the signal
728    pub fn stop_in_debug(&mut self, dbg: &mut DBG, state: bool) {
729        self.tim.stop_in_debug(dbg, state);
730    }
731}
732
733impl<TIM: Instance + MasterTimer, const FREQ: u32> FTimer<TIM, FREQ> {
734    pub fn set_master_mode(&mut self, mode: TIM::Mms) {
735        self.tim.master_mode(mode)
736    }
737}
738
739#[inline(always)]
740const fn compute_arr_presc(freq: u32, clock: u32) -> (u16, u32) {
741    let ticks = clock / freq;
742    let psc = (ticks - 1) / (1 << 16);
743    let arr = ticks / (psc + 1) - 1;
744    (psc as u16, arr)
745}
746
747hal!(
748    pac::TIM2: [Timer2, u16, dbg_tim2_stop, c: (CH4), m: tim2,],
749    pac::TIM3: [Timer3, u16, dbg_tim3_stop, c: (CH4), m: tim2,],
750);
751
752#[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity",))]
753hal!(
754    pac::TIM1: [Timer1, u16, dbg_tim1_stop, c: (CH4, _aoe), m: tim1,],
755);
756
757#[cfg(any(feature = "stm32f100", feature = "high", feature = "connectivity",))]
758hal! {
759    pac::TIM6: [Timer6, u16, dbg_tim6_stop, m: tim6,],
760}
761
762#[cfg(any(
763    all(feature = "high", any(feature = "stm32f101", feature = "stm32f103",),),
764    any(feature = "stm32f100", feature = "connectivity",)
765))]
766hal! {
767    pac::TIM7: [Timer7, u16, dbg_tim7_stop, m: tim6,],
768}
769
770#[cfg(feature = "stm32f100")]
771hal! {
772    pac::TIM15: [Timer15, u16, dbg_tim15_stop, c: (CH2),],
773    pac::TIM16: [Timer16, u16, dbg_tim16_stop, c: (CH1),],
774    pac::TIM17: [Timer17, u16, dbg_tim17_stop, c: (CH1),],
775}
776
777#[cfg(feature = "medium")]
778hal! {
779    pac::TIM4: [Timer4, u16, dbg_tim4_stop, c: (CH4), m: tim2,],
780}
781
782#[cfg(any(feature = "high", feature = "connectivity"))]
783hal! {
784    pac::TIM5: [Timer5, u16, dbg_tim5_stop, c: (CH4), m: tim2,],
785}
786
787#[cfg(all(feature = "stm32f103", feature = "high",))]
788hal! {
789    pac::TIM8: [Timer8, u16, dbg_tim8_stop, c: (CH4, _aoe), m: tim1,],
790}
791
792//TODO: restore these timers once stm32-rs has been updated
793/*
794 *   dbg_tim(12-13)_stop fields missing from 103 xl in stm32-rs
795 *   dbg_tim(9-10)_stop fields missing from 101 xl in stm32-rs
796#[cfg(any(
797    feature = "xl",
798    all(
799        feature = "stm32f100",
800        feature = "high",
801)))]
802hal! {
803    TIM12: (tim12, dbg_tim12_stop),
804    TIM13: (tim13, dbg_tim13_stop),
805    TIM14: (tim14, dbg_tim14_stop),
806}
807#[cfg(feature = "xl")]
808hal! {
809    TIM9: (tim9, dbg_tim9_stop),
810    TIM10: (tim10, dbg_tim10_stop),
811    TIM11: (tim11, dbg_tim11_stop),
812}
813*/