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            unsafe { self.set_auto_reload_unchecked(arr) }
61            Ok(())
62        } else {
63            Err(Error::WrongAutoReload)
64        }
65    }
66
67    #[inline(always)]
68    fn read_auto_reload(&self) -> u32 {
69        self.arr().read().bits()
70    }
71
72    #[inline(always)]
73    fn set_prescaler(&mut self, psc: u16) {
74        self.psc().write(|w| w.psc().set(psc));
75    }
76
77    #[inline(always)]
78    fn read_prescaler(&self) -> u16 {
79        self.psc().read().psc().bits()
80    }
81
82    #[inline(always)]
83    fn read_count(&self) -> u32 {
84        self.cnt().read().bits()
85    }
86
87    #[inline(always)]
88    fn trigger_update(&mut self) {
89        // Sets the URS bit to prevent an interrupt from being triggered by
90        // the UG bit
91        self.cr1().modify(|_, w| w.urs().set_bit());
92        self.egr().write(|w| w.ug().set_bit());
93        self.cr1().modify(|_, w| w.urs().clear_bit());
94    }
95
96    #[inline]
97    fn config_freq(&mut self, clock: Hertz, update_freq: Hertz) {
98        let (prescaler, arr) = compute_prescaler_arr(clock.raw(), update_freq.raw());
99        self.set_prescaler(prescaler as u16);
100        self.set_auto_reload(arr).unwrap();
101        // Trigger update event to load the registers
102        self.trigger_update();
103    }
104
105    #[inline(always)]
106    fn clear_interrupt_flag(&mut self, event: Event) {
107        self.sr()
108            .write(|w| unsafe { w.bits(0xffff & !event.bits()) });
109    }
110
111    #[inline(always)]
112    fn listen_interrupt(&mut self, event: Event, b: bool) {
113        self.dier().modify(|r, w| unsafe {
114            w.bits(if b {
115                r.bits() | event.bits()
116            } else {
117                r.bits() & !event.bits()
118            })
119        });
120    }
121
122    #[inline(always)]
123    fn get_interrupt_flag(&self) -> Event {
124        Event::from_bits_truncate(self.sr().read().bits())
125    }
126
127    #[inline(always)]
128    fn start_one_pulse(&mut self) {
129        self.cr1().modify(|_, w| w.opm().set_bit().cen().set_bit());
130    }
131
132    #[inline(always)]
133    fn stop_in_debug(&mut self, state: bool) {
134        let dbg = unsafe { DBG::steal() };
135        // sync dbg_t1
136        dbg.cr().modify(|_, w| w.dbg_tim1_stop().bit(state));
137        // sync dbg_end
138    }
139
140    #[inline(always)]
141    fn enable_preload(&mut self, b: bool) {
142        self.cr1().modify(|_, w| w.arpe().bit(b));
143    }
144}
145
146// sync pwm
147// PWM ------------------------------------------------------------------------
148
149impl TimerWithPwm for TimerX {
150    fn stop_pwm(&mut self) {
151        self.disable_counter();
152    }
153
154    // sync start_pwm_aoe
155
156    #[inline(always)]
157    fn start_pwm(&mut self) {
158        // self.bdtr().modify(|_, w| w.moe().set_bit());
159        self.bdtr().modify(|_, w| w.aoe().set_bit());
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
410
411use pac::tim1::cr2::MMS;
412impl From<MasterMode> for MMS {
413    fn from(value: MasterMode) -> Self {
414        match value {
415            MasterMode::Reset => MMS::Reset,
416            MasterMode::Enable => MMS::Enable,
417            MasterMode::Update => MMS::Update,
418            MasterMode::ComparePulse => MMS::ComparePulse,
419            MasterMode::CompareOc1 => MMS::CompareOc1,
420            MasterMode::CompareOc2 => MMS::CompareOc2,
421            MasterMode::CompareOc3 => MMS::CompareOc3,
422            MasterMode::CompareOc4 => MMS::CompareOc4,
423        }
424    }
425}