stm32f1_hal/timer/
timer5.rs

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