stm32f1_hal/timer/
timer3.rs

1type TimerX = pac::TIM3;
2type Width = u16;
3
4// Do NOT manually modify the code between begin and end!
5// It's synced by scripts/sync_code.py.
6// sync begin
7
8use super::*;
9use crate::{Mcu, pac};
10
11impl Instance for TimerX {}
12
13impl TimerInit<TimerX> for TimerX {
14    fn constrain(self, mcu: &mut Mcu) -> Timer<TimerX> {
15        Timer::new(self, mcu)
16    }
17}
18
19impl GeneralTimer for TimerX {
20    #[inline(always)]
21    fn reset_config(&mut self) {
22        self.cr1().reset();
23    }
24
25    #[inline(always)]
26    fn enable_counter(&mut self) {
27        self.cr1().modify(|_, w| w.cen().set_bit());
28    }
29
30    #[inline(always)]
31    fn disable_counter(&mut self) {
32        self.cr1().modify(|_, w| w.cen().clear_bit());
33    }
34
35    #[inline(always)]
36    fn is_counter_enabled(&self) -> bool {
37        self.cr1().read().cen().is_enabled()
38    }
39
40    #[inline(always)]
41    fn reset_counter(&mut self) {
42        self.cnt().reset();
43    }
44
45    #[inline(always)]
46    fn max_auto_reload() -> u32 {
47        Width::MAX as u32
48    }
49
50    #[inline(always)]
51    unsafe fn set_auto_reload_unchecked(&mut self, arr: u32) {
52        unsafe {
53            self.arr().write(|w| w.bits(arr));
54        }
55    }
56
57    #[inline(always)]
58    fn set_auto_reload(&mut self, arr: u32) -> Result<(), Error> {
59        // Note: Make it impossible to set the ARR value to 0, since this
60        // would cause an infinite loop.
61        if arr > 0 && arr <= Self::max_auto_reload() {
62            Ok(unsafe { self.set_auto_reload_unchecked(arr) })
63        } else {
64            Err(Error::WrongAutoReload)
65        }
66    }
67
68    #[inline(always)]
69    fn read_auto_reload(&self) -> u32 {
70        self.arr().read().bits()
71    }
72
73    #[inline(always)]
74    fn set_prescaler(&mut self, psc: u16) {
75        self.psc().write(|w| w.psc().set(psc));
76    }
77
78    #[inline(always)]
79    fn read_prescaler(&self) -> u16 {
80        self.psc().read().psc().bits()
81    }
82
83    #[inline(always)]
84    fn read_count(&self) -> u32 {
85        self.cnt().read().bits() as u32
86    }
87
88    #[inline(always)]
89    fn trigger_update(&mut self) {
90        // Sets the URS bit to prevent an interrupt from being triggered by
91        // the UG bit
92        self.cr1().modify(|_, w| w.urs().set_bit());
93        self.egr().write(|w| w.ug().set_bit());
94        self.cr1().modify(|_, w| w.urs().clear_bit());
95    }
96
97    #[inline]
98    fn config_freq(&mut self, clock: Hertz, update_freq: Hertz) {
99        let (prescaler, arr) = compute_prescaler_arr(clock.raw(), update_freq.raw());
100        self.set_prescaler(prescaler as u16);
101        self.set_auto_reload(arr).unwrap();
102        // Trigger update event to load the registers
103        self.trigger_update();
104    }
105
106    #[inline(always)]
107    fn clear_interrupt_flag(&mut self, event: Event) {
108        self.sr()
109            .write(|w| unsafe { w.bits(0xffff & !event.bits()) });
110    }
111
112    #[inline(always)]
113    fn listen_interrupt(&mut self, event: Event, b: bool) {
114        self.dier().modify(|r, w| unsafe {
115            w.bits(if b {
116                r.bits() | event.bits()
117            } else {
118                r.bits() & !event.bits()
119            })
120        });
121    }
122
123    #[inline(always)]
124    fn get_interrupt_flag(&self) -> Event {
125        Event::from_bits_truncate(self.sr().read().bits())
126    }
127
128    #[inline(always)]
129    fn start_one_pulse(&mut self) {
130        self.cr1().modify(|_, w| w.opm().set_bit().cen().set_bit());
131    }
132
133    #[inline(always)]
134    fn stop_in_debug(&mut self, state: bool) {
135        let dbg = unsafe { DBG::steal() };
136        // sync dbg_t3
137        dbg.cr().modify(|_, w| w.dbg_tim3_stop().bit(state));
138        // sync dbg_end
139    }
140
141    #[inline(always)]
142    fn enable_preload(&mut self, b: bool) {
143        self.cr1().modify(|_, w| w.arpe().bit(b));
144    }
145}
146
147// sync pwm
148// PWM ------------------------------------------------------------------------
149
150impl TimerWithPwm for TimerX {
151    fn stop_pwm(&mut self) {
152        self.disable_counter();
153    }
154
155    // sync start_pwm
156
157    #[inline(always)]
158    fn start_pwm(&mut self) {
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