1#![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
78pub 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#[derive(Clone, Copy, PartialEq, Eq)]
95pub enum SysEvent {
96 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 Disabled,
114 WrongAutoReload,
115}
116
117pub trait TimerExt: Sized {
118 fn counter<const FREQ: u32>(self, clocks: &Clocks) -> Counter<Self, FREQ>;
120 fn counter_ms(self, clocks: &Clocks) -> CounterMs<Self> {
126 self.counter::<1_000>(clocks)
127 }
128 fn counter_us(self, clocks: &Clocks) -> CounterUs<Self> {
132 self.counter::<1_000_000>(clocks)
133 }
134 fn counter_hz(self, clocks: &Clocks) -> CounterHz<Self>;
136
137 fn delay<const FREQ: u32>(self, clocks: &Clocks) -> Delay<Self, FREQ>;
139 fn delay_ms(self, clocks: &Clocks) -> DelayMs<Self> {
145 self.delay::<1_000>(clocks)
146 }
147 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 fn counter_hz(self, clocks: &Clocks) -> SysCounterHz;
170
171 fn counter<const FREQ: u32>(self, clocks: &Clocks) -> SysCounter<FREQ>;
173 fn counter_us(self, clocks: &Clocks) -> SysCounterUs {
175 self.counter::<1_000_000>(clocks)
176 }
177 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 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 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 pub fn listen(&mut self, event: SysEvent) {
228 match event {
229 SysEvent::Update => self.tim.enable_interrupt(),
230 }
231 }
232
233 pub fn unlisten(&mut self, event: SysEvent) {
235 match event {
236 SysEvent::Update => self.tim.disable_interrupt(),
237 }
238 }
239
240 pub fn reset(&mut self) {
242 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 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 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 pub fn new(tim: TIM, clocks: &Clocks) -> Self {
585 unsafe {
586 let rcc = &(*RCC::ptr());
588 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 pub fn listen(&mut self, event: Event) {
616 self.tim.listen_interrupt(event, true);
617 }
618
619 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 pub fn unlisten(&mut self, event: Event) {
633 self.tim.listen_interrupt(event, false);
634 }
635
636 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
648pub struct FTimer<TIM, const FREQ: u32> {
652 tim: TIM,
653}
654
655pub type FTimerUs<TIM> = FTimer<TIM, 1_000_000>;
657
658pub type FTimerMs<TIM> = FTimer<TIM, 1_000>;
662
663impl<TIM: Instance, const FREQ: u32> FTimer<TIM, FREQ> {
664 pub fn new(tim: TIM, clocks: &Clocks) -> Self {
666 unsafe {
667 let rcc = &(*RCC::ptr());
669 TIM::enable(rcc);
671 TIM::reset(rcc);
672 }
673
674 let mut t = Self { tim };
675 t.configure(clocks);
676 t
677 }
678
679 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 pub fn counter(self) -> Counter<TIM, FREQ> {
689 Counter(self)
690 }
691
692 pub fn delay(self) -> Delay<TIM, FREQ> {
694 Delay(self)
695 }
696
697 pub fn release(self) -> TIM {
699 self.tim
700 }
701
702 pub fn listen(&mut self, event: Event) {
707 self.tim.listen_interrupt(event, true);
708 }
709
710 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 pub fn unlisten(&mut self, event: Event) {
724 self.tim.listen_interrupt(event, false);
725 }
726
727 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