stm32f1_hal/timer/
timer1.rs

1type TimerX = pac::TIM1;
2type Width = u16;
3
4// sync begin
5
6use super::*;
7use crate::{Mcu, pac};
8
9impl Instance for TimerX {}
10
11impl TimerInit<TimerX> for TimerX {
12    fn constrain(self, mcu: &mut Mcu) -> Timer<TimerX> {
13        Timer::new(self, mcu)
14    }
15}
16
17impl GeneralTimer for TimerX {
18    #[inline(always)]
19    fn reset_config(&mut self) {
20        self.cr1().reset();
21    }
22
23    #[inline(always)]
24    fn enable_counter(&mut self) {
25        self.cr1().modify(|_, w| w.cen().set_bit());
26    }
27
28    #[inline(always)]
29    fn disable_counter(&mut self) {
30        self.cr1().modify(|_, w| w.cen().clear_bit());
31    }
32
33    #[inline(always)]
34    fn is_counter_enabled(&self) -> bool {
35        self.cr1().read().cen().is_enabled()
36    }
37
38    #[inline(always)]
39    fn reset_counter(&mut self) {
40        self.cnt().reset();
41    }
42
43    #[inline(always)]
44    fn max_auto_reload() -> u32 {
45        Width::MAX as u32
46    }
47
48    #[inline(always)]
49    unsafe fn set_auto_reload_unchecked(&mut self, arr: u32) {
50        unsafe {
51            self.arr().write(|w| w.bits(arr));
52        }
53    }
54
55    #[inline(always)]
56    fn set_auto_reload(&mut self, arr: u32) -> Result<(), Error> {
57        // Note: Make it impossible to set the ARR value to 0, since this
58        // would cause an infinite loop.
59        if arr > 0 && arr <= Self::max_auto_reload() {
60            Ok(unsafe { self.set_auto_reload_unchecked(arr) })
61        } else {
62            Err(Error::WrongAutoReload)
63        }
64    }
65
66    #[inline(always)]
67    fn read_auto_reload(&self) -> u32 {
68        self.arr().read().bits()
69    }
70
71    #[inline(always)]
72    fn set_prescaler(&mut self, psc: u16) {
73        self.psc().write(|w| w.psc().set(psc));
74    }
75
76    #[inline(always)]
77    fn read_prescaler(&self) -> u16 {
78        self.psc().read().psc().bits()
79    }
80
81    #[inline(always)]
82    fn read_count(&self) -> u32 {
83        self.cnt().read().bits() as u32
84    }
85
86    #[inline(always)]
87    fn trigger_update(&mut self) {
88        // Sets the URS bit to prevent an interrupt from being triggered by
89        // the UG bit
90        self.cr1().modify(|_, w| w.urs().set_bit());
91        self.egr().write(|w| w.ug().set_bit());
92        self.cr1().modify(|_, w| w.urs().clear_bit());
93    }
94
95    #[inline]
96    fn config_freq(&mut self, clock: Hertz, update_freq: Hertz) {
97        let (prescaler, arr) = compute_prescaler_arr(clock.raw(), update_freq.raw());
98        self.set_prescaler(prescaler as u16);
99        self.set_auto_reload(arr).unwrap();
100        // Trigger update event to load the registers
101        self.trigger_update();
102    }
103
104    #[inline(always)]
105    fn clear_interrupt_flag(&mut self, event: Event) {
106        self.sr()
107            .write(|w| unsafe { w.bits(0xffff & !event.bits()) });
108    }
109
110    #[inline(always)]
111    fn listen_interrupt(&mut self, event: Event, b: bool) {
112        self.dier().modify(|r, w| unsafe {
113            w.bits(if b {
114                r.bits() | event.bits()
115            } else {
116                r.bits() & !event.bits()
117            })
118        });
119    }
120
121    #[inline(always)]
122    fn get_interrupt_flag(&self) -> Event {
123        Event::from_bits_truncate(self.sr().read().bits())
124    }
125
126    #[inline(always)]
127    fn start_one_pulse(&mut self) {
128        self.cr1().modify(|_, w| w.opm().set_bit().cen().set_bit());
129    }
130
131    #[inline(always)]
132    fn stop_in_debug(&mut self, state: bool) {
133        let dbg = unsafe { DBG::steal() };
134        // sync dbg_t1
135        dbg.cr().modify(|_, w| w.dbg_tim1_stop().bit(state));
136        // sync dbg_end
137    }
138
139    #[inline(always)]
140    fn enable_preload(&mut self, b: bool) {
141        self.cr1().modify(|_, w| w.arpe().bit(b));
142    }
143}
144
145// sync pwm
146// PWM ------------------------------------------------------------------------
147
148impl TimerWithPwm for TimerX {
149    fn stop_pwm(&mut self) {
150        self.disable_counter();
151    }
152
153    // sync start_pwm_aoe
154
155    #[inline(always)]
156    fn start_pwm(&mut self) {
157        // self.bdtr().modify(|_, w| w.moe().set_bit());
158        self.bdtr().modify(|_, w| w.aoe().set_bit());
159        self.reset_counter();
160        self.enable_counter();
161    }
162
163    // sync pwm_cfg_4
164
165    #[inline(always)]
166    fn preload_output_channel_in_mode(&mut self, channel: Channel, mode: PwmMode) {
167        let mode = Ocm::from(mode);
168        match channel {
169            Channel::C1 => {
170                self.ccmr1_output()
171                    .modify(|_, w| w.oc1pe().set_bit().oc1m().set(mode as _));
172            }
173            Channel::C2 => {
174                self.ccmr1_output()
175                    .modify(|_, w| w.oc2pe().set_bit().oc2m().set(mode as _));
176            }
177            Channel::C3 => {
178                self.ccmr2_output()
179                    .modify(|_, w| w.oc3pe().set_bit().oc3m().set(mode as _));
180            }
181            Channel::C4 => {
182                self.ccmr2_output()
183                    .modify(|_, w| w.oc4pe().set_bit().oc4m().set(mode as _));
184            }
185        }
186    }
187
188    fn set_polarity(&mut self, channel: Channel, polarity: PwmPolarity) {
189        match channel {
190            Channel::C1 => {
191                self.ccer()
192                    .modify(|_, w| w.cc1p().bit(polarity == PwmPolarity::ActiveLow));
193            }
194            Channel::C2 => {
195                self.ccer()
196                    .modify(|_, w| w.cc2p().bit(polarity == PwmPolarity::ActiveLow));
197            }
198            Channel::C3 => {
199                self.ccer()
200                    .modify(|_, w| w.cc3p().bit(polarity == PwmPolarity::ActiveLow));
201            }
202            Channel::C4 => {
203                self.ccer()
204                    .modify(|_, w| w.cc4p().bit(polarity == PwmPolarity::ActiveLow));
205            }
206        }
207    }
208}
209
210// sync pwm_ch1
211// PWM Channels ---------------------------------------------------------------
212
213impl TimerWithPwm1Ch for TimerX {
214    #[inline(always)]
215    fn enable_ch1(&mut self, en: bool) {
216        self.ccer().modify(|_, w| w.cc1e().bit(en));
217    }
218
219    #[inline(always)]
220    fn set_ch1_cc_value(&mut self, value: u32) {
221        unsafe { self.ccr1().write(|w| w.bits(value)) };
222    }
223
224    #[inline(always)]
225    fn get_ch1_cc_value(&self) -> u32 {
226        self.ccr1().read().bits()
227    }
228}
229
230// sync pwm_ch2
231
232impl TimerWithPwm2Ch for TimerX {
233    #[inline(always)]
234    fn enable_ch2(&mut self, en: bool) {
235        self.ccer().modify(|_, w| w.cc2e().bit(en));
236    }
237
238    #[inline(always)]
239    fn set_ch2_cc_value(&mut self, value: u32) {
240        unsafe { self.ccr2().write(|w| w.bits(value)) };
241    }
242
243    #[inline(always)]
244    fn get_ch2_cc_value(&self) -> u32 {
245        self.ccr2().read().bits()
246    }
247}
248
249// sync pwm_ch4
250
251impl TimerWithPwm3Ch for TimerX {
252    #[inline(always)]
253    fn enable_ch3(&mut self, en: bool) {
254        self.ccer().modify(|_, w| w.cc3e().bit(en));
255    }
256
257    #[inline(always)]
258    fn set_ch3_cc_value(&mut self, value: u32) {
259        unsafe { self.ccr3().write(|w| w.bits(value)) };
260    }
261
262    #[inline(always)]
263    fn get_ch3_cc_value(&self) -> u32 {
264        self.ccr3().read().bits()
265    }
266}
267
268impl TimerWithPwm4Ch for TimerX {
269    #[inline(always)]
270    fn enable_ch4(&mut self, en: bool) {
271        self.ccer().modify(|_, w| w.cc4e().bit(en));
272    }
273
274    #[inline(always)]
275    fn set_ch4_cc_value(&mut self, value: u32) {
276        unsafe { self.ccr4().write(|w| w.bits(value)) };
277    }
278
279    #[inline(always)]
280    fn get_ch4_cc_value(&self) -> u32 {
281        self.ccr4().read().bits()
282    }
283}
284
285// Other ----------------------------------------------------------------------
286
287// sync master
288impl MasterTimer for TimerX {
289    #[inline(always)]
290    fn master_mode(&mut self, mode: MasterMode) {
291        self.cr2().modify(|_, w| w.mms().variant(mode.into()));
292    }
293}
294
295// sync dir
296
297impl TimerDirection for TimerX {
298    #[inline(always)]
299    fn set_count_direction(&mut self, dir: CountDirection) {
300        self.cr1()
301            .modify(|_, w| w.dir().bit(dir == CountDirection::Down));
302    }
303}
304
305// sync RTIC
306#[cfg(feature = "rtic")]
307mod timer_rtic {
308    use super::*;
309    use crate::Mcu;
310    use rtic_monotonic::Monotonic;
311
312    impl MonoTimerExt for TimerX {
313        fn monotonic<const FREQ: u32>(self, mcu: &mut Mcu) -> MonoTimer<Self, FREQ> {
314            mcu.rcc.enable(&self);
315            mcu.rcc.reset(&self);
316            let clk = mcu.rcc.get_timer_clock(&self);
317            FTimer::new(self, clk).monotonic()
318        }
319    }
320
321    impl<const FREQ: u32> FTimer<TimerX, FREQ> {
322        pub fn monotonic(self) -> MonoTimer<TimerX, FREQ> {
323            MonoTimer::<TimerX, FREQ>::_new(self)
324        }
325    }
326
327    impl<const FREQ: u32> MonoTimer<TimerX, FREQ> {
328        fn _new(timer: FTimer<TimerX, FREQ>) -> Self {
329            // Set auto-reload value.
330            timer.tim.arr().write(|w| w.arr().set(u16::MAX));
331            // Generate interrupt on overflow.
332            timer.tim.egr().write(|w| w.ug().set_bit());
333
334            // Start timer.
335            // Clear interrupt flag.
336            timer.tim.sr().modify(|_, w| w.uif().clear_bit());
337            timer.tim.cr1().modify(|_, w| {
338                // Enable counter.
339                w.cen().set_bit();
340                // Overflow should trigger update event.
341                w.udis().clear_bit();
342                // Only overflow triggers interrupt.
343                w.urs().set_bit()
344            });
345
346            Self { timer, ovf: 0 }
347        }
348    }
349
350    impl<const FREQ: u32> Monotonic for MonoTimer<TimerX, FREQ> {
351        type Instant = fugit::TimerInstantU32<FREQ>;
352        type Duration = fugit::TimerDurationU32<FREQ>;
353
354        unsafe fn reset(&mut self) {
355            self.tim.dier().modify(|_, w| w.cc1ie().set_bit());
356        }
357
358        #[inline(always)]
359        fn now(&mut self) -> Self::Instant {
360            let cnt = self.tim.cnt().read().cnt().bits() as u32;
361
362            // If the overflow bit is set, we add this to the timer value. It means the `on_interrupt`
363            // has not yet happened, and we need to compensate here.
364            let ovf = if self.tim.sr().read().uif().bit_is_set() {
365                0x10000
366            } else {
367                0
368            };
369
370            Self::Instant::from_ticks(cnt.wrapping_add(ovf).wrapping_add(self.ovf))
371        }
372
373        fn set_compare(&mut self, instant: Self::Instant) {
374            let now = self.now();
375            let cnt = self.tim.cnt().read().cnt().bits();
376
377            // Since the timer may or may not overflow based on the requested compare val, we check
378            // how many ticks are left.
379            let val = match instant.checked_duration_since(now) {
380                None => cnt.wrapping_add(0xffff), // In the past, RTIC will handle this
381                Some(x) if x.ticks() <= 0xffff => instant.duration_since_epoch().ticks() as u16, // Will not overflow
382                Some(_) => cnt.wrapping_add(0xffff), // Will overflow, run for as long as possible
383            };
384
385            self.tim.ccr1().write(|w| w.ccr().set(val));
386        }
387
388        fn clear_compare_flag(&mut self) {
389            self.tim.sr().modify(|_, w| w.cc1if().clear_bit());
390        }
391
392        fn on_interrupt(&mut self) {
393            // If there was an overflow, increment the overflow counter.
394            if self.tim.sr().read().uif().bit_is_set() {
395                self.tim.sr().modify(|_, w| w.uif().clear_bit());
396
397                self.ovf += 0x10000;
398            }
399        }
400
401        #[inline(always)]
402        fn zero() -> Self::Instant {
403            Self::Instant::from_ticks(0)
404        }
405    }
406}
407
408// sync end
409
410use pac::tim1::cr2::MMS;
411impl From<MasterMode> for MMS {
412    fn from(value: MasterMode) -> Self {
413        match value {
414            MasterMode::Reset => MMS::Reset,
415            MasterMode::Enable => MMS::Enable,
416            MasterMode::Update => MMS::Update,
417            MasterMode::ComparePulse => MMS::ComparePulse,
418            MasterMode::CompareOc1 => MMS::CompareOc1,
419            MasterMode::CompareOc2 => MMS::CompareOc2,
420            MasterMode::CompareOc3 => MMS::CompareOc3,
421            MasterMode::CompareOc4 => MMS::CompareOc4,
422        }
423    }
424}