1#![allow(non_upper_case_globals)]
50
51use crate::bb;
52use crate::pac::{self, DBGMCU as DBG};
53
54use crate::rcc::{self, Clocks, Rcc};
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(crate) mod pins;
66pub mod pwm_input;
67pub use pins::*;
68pub mod delay;
69pub use delay::*;
70pub mod counter;
71pub use counter::*;
72pub mod pwm;
73pub use pwm::*;
74
75mod hal_02;
76mod hal_1;
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, rcc: &mut Rcc) -> Counter<Self, FREQ>;
120 fn counter_ms(self, rcc: &mut Rcc) -> CounterMs<Self> {
126 self.counter::<1_000>(rcc)
127 }
128 fn counter_us(self, rcc: &mut Rcc) -> CounterUs<Self> {
132 self.counter::<1_000_000>(rcc)
133 }
134 fn counter_hz(self, rcc: &mut Rcc) -> CounterHz<Self>;
136
137 fn delay<const FREQ: u32>(self, rcc: &mut Rcc) -> Delay<Self, FREQ>;
139 fn delay_ms(self, rcc: &mut Rcc) -> DelayMs<Self> {
145 self.delay::<1_000>(rcc)
146 }
147 fn delay_us(self, rcc: &mut Rcc) -> DelayUs<Self> {
151 self.delay::<1_000_000>(rcc)
152 }
153}
154
155impl<TIM: Instance> TimerExt for TIM {
156 fn counter<const FREQ: u32>(self, rcc: &mut Rcc) -> Counter<Self, FREQ> {
157 FTimer::new(self, rcc).counter()
158 }
159 fn counter_hz(self, rcc: &mut Rcc) -> CounterHz<Self> {
160 Timer::new(self, rcc).counter_hz()
161 }
162 fn delay<const FREQ: u32>(self, rcc: &mut Rcc) -> Delay<Self, FREQ> {
163 FTimer::new(self, rcc).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().set(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 self.dier().modify(|r, w| unsafe { w.bits(
388 if b {
389 r.bits() | event.bits()
390 } else {
391 r.bits() & !event.bits()
392 }
393 ) });
394 }
395 #[inline(always)]
396 fn get_interrupt_flag(&self) -> Event {
397 Event::from_bits_truncate(self.sr().read().bits())
398 }
399 #[inline(always)]
400 fn read_count(&self) -> Self::Width {
401 self.cnt().read().bits() as Self::Width
402 }
403 #[inline(always)]
404 fn start_one_pulse(&mut self) {
405 self.cr1().modify(|_, w| w.opm().set_bit().cen().set_bit());
406 }
407 #[inline(always)]
408 fn cr1_reset(&mut self) {
409 self.cr1().reset();
410 }
411 #[inline(always)]
412 fn stop_in_debug(&mut self, dbg: &mut DBG, state: bool) {
413 dbg.cr().modify(|_, w| w.$dbg_timX_stop().bit(state));
414 }
415 }
416 $(with_pwm!($TIM: $cnum $(, $aoe)?);)?
417
418 $(impl MasterTimer for $TIM {
419 type Mms = pac::$timbase::cr2::MMS;
420 fn master_mode(&mut self, mode: Self::Mms) {
421 self.cr2().modify(|_,w| w.mms().variant(mode));
422 }
423 })?
424 )+
425 }
426}
427
428macro_rules! with_pwm {
429 ($TIM:ty: CH1) => {
430 impl WithPwm for $TIM {
431 const CH_NUMBER: u8 = 1;
432
433 #[inline(always)]
434 fn read_cc_value(channel: u8) -> u32 {
435 let tim = unsafe { &*<$TIM>::ptr() };
436 if channel < Self::CH_NUMBER {
437 tim.ccr(channel as usize).read().bits()
438 } else {
439 0
440 }
441 }
442
443 #[inline(always)]
444 fn set_cc_value(channel: u8, value: u32) {
445 let tim = unsafe { &*<$TIM>::ptr() };
446 #[allow(unused_unsafe)]
447 if channel < Self::CH_NUMBER {
448 tim.ccr(channel as usize).write(|w| unsafe { w.bits(value) });
449 }
450 }
451
452 #[inline(always)]
453 fn preload_output_channel_in_mode(&mut self, channel: Channel, mode: Ocm) {
454 match channel {
455 Channel::C1 => {
456 self.ccmr1_output()
457 .modify(|_, w| w.oc1pe().set_bit().oc1m().set(mode as _) );
458 }
459 _ => {},
460 }
461 }
462
463 #[inline(always)]
464 fn start_pwm(&mut self) {
465 self.cr1().modify(|_, w| w.cen().set_bit());
466 }
467
468 #[inline(always)]
469 fn enable_channel(c: u8, b: bool) {
470 let tim = unsafe { &*<$TIM>::ptr() };
471 if c < Self::CH_NUMBER {
472 unsafe { bb::write(tim.ccer(), c*4, b); }
473 }
474 }
475 }
476 };
477 ($TIM:ty: CH2) => {
478 impl WithPwm for $TIM {
479 const CH_NUMBER: u8 = 2;
480
481 #[inline(always)]
482 fn read_cc_value(channel: u8) -> u32 {
483 let tim = unsafe { &*<$TIM>::ptr() };
484 if channel < Self::CH_NUMBER {
485 tim.ccr(channel as usize).read().bits()
486 } else {
487 0
488 }
489 }
490
491 #[inline(always)]
492 fn set_cc_value(channel: u8, value: u32) {
493 let tim = unsafe { &*<$TIM>::ptr() };
494 #[allow(unused_unsafe)]
495 if channel < Self::CH_NUMBER {
496 tim.ccr(channel as usize).write(|w| unsafe { w.bits(value) });
497 }
498 }
499
500 #[inline(always)]
501 fn preload_output_channel_in_mode(&mut self, channel: Channel, mode: Ocm) {
502 match channel {
503 Channel::C1 => {
504 self.ccmr1_output()
505 .modify(|_, w| w.oc1pe().set_bit().oc1m().set(mode as _) );
506 }
507 Channel::C2 => {
508 self.ccmr1_output()
509 .modify(|_, w| w.oc2pe().set_bit().oc2m().set(mode as _) );
510 }
511 _ => {},
512 }
513 }
514
515 #[inline(always)]
516 fn start_pwm(&mut self) {
517 self.cr1().modify(|_, w| w.cen().set_bit());
518 }
519
520 #[inline(always)]
521 fn enable_channel(c: u8, b: bool) {
522 let tim = unsafe { &*<$TIM>::ptr() };
523 if c < Self::CH_NUMBER {
524 unsafe { bb::write(tim.ccer(), c*4, b); }
525 }
526 }
527 }
528 };
529 ($TIM:ty: CH4 $(, $aoe:ident)?) => {
530 impl WithPwm for $TIM {
531 const CH_NUMBER: u8 = 4;
532
533 #[inline(always)]
534 fn read_cc_value(channel: u8) -> u32 {
535 let tim = unsafe { &*<$TIM>::ptr() };
536 tim.ccr(channel as usize).read().bits()
537 }
538
539 #[inline(always)]
540 fn set_cc_value(channel: u8, value: u32) {
541 let tim = unsafe { &*<$TIM>::ptr() };
542 tim.ccr(channel as usize).write(|w| unsafe { w.bits(value) });
543 }
544
545 #[inline(always)]
546 fn preload_output_channel_in_mode(&mut self, channel: Channel, mode: Ocm) {
547 match channel {
548 Channel::C1 => {
549 self.ccmr1_output()
550 .modify(|_, w| w.oc1pe().set_bit().oc1m().set(mode as _) );
551 }
552 Channel::C2 => {
553 self.ccmr1_output()
554 .modify(|_, w| w.oc2pe().set_bit().oc2m().set(mode as _) );
555 }
556 Channel::C3 => {
557 self.ccmr2_output()
558 .modify(|_, w| w.oc3pe().set_bit().oc3m().set(mode as _) );
559 }
560 Channel::C4 => {
561 self.ccmr2_output()
562 .modify(|_, w| w.oc4pe().set_bit().oc4m().set(mode as _) );
563 }
564 }
565 }
566
567 #[inline(always)]
568 fn start_pwm(&mut self) {
569 $(let $aoe = self.bdtr().modify(|_, w| w.aoe().set_bit());)?
570 self.cr1().modify(|_, w| w.cen().set_bit());
571 }
572
573 #[inline(always)]
574 fn enable_channel(c: u8, b: bool) {
575 let tim = unsafe { &*<$TIM>::ptr() };
576 if c < Self::CH_NUMBER {
577 unsafe { bb::write(tim.ccer(), c*4, b); }
578 }
579 }
580 }
581 }
582}
583
584impl<TIM: Instance> Timer<TIM> {
585 pub fn new(tim: TIM, rcc: &mut Rcc) -> Self {
587 TIM::enable(rcc);
589 TIM::reset(rcc);
590
591 Self {
592 clk: TIM::timer_clock(&rcc.clocks),
593 tim,
594 }
595 }
596
597 pub fn configure(&mut self, clocks: &Clocks) {
598 self.clk = TIM::timer_clock(clocks);
599 }
600
601 pub fn counter_hz(self) -> CounterHz<TIM> {
602 CounterHz(self)
603 }
604
605 pub fn release(self) -> TIM {
606 self.tim
607 }
608
609 pub fn listen(&mut self, event: Event) {
614 self.tim.listen_interrupt(event, true);
615 }
616
617 pub fn clear_interrupt(&mut self, event: Event) {
622 self.tim.clear_interrupt_flag(event);
623 }
624
625 pub fn get_interrupt(&mut self) -> Event {
626 self.tim.get_interrupt_flag()
627 }
628
629 pub fn unlisten(&mut self, event: Event) {
631 self.tim.listen_interrupt(event, false);
632 }
633
634 pub fn stop_in_debug(&mut self, dbg: &mut DBG, state: bool) {
636 self.tim.stop_in_debug(dbg, state);
637 }
638}
639
640impl<TIM: Instance + MasterTimer> Timer<TIM> {
641 pub fn set_master_mode(&mut self, mode: TIM::Mms) {
642 self.tim.master_mode(mode)
643 }
644}
645
646pub struct FTimer<TIM, const FREQ: u32> {
650 tim: TIM,
651}
652
653pub type FTimerUs<TIM> = FTimer<TIM, 1_000_000>;
655
656pub type FTimerMs<TIM> = FTimer<TIM, 1_000>;
660
661impl<TIM: Instance, const FREQ: u32> FTimer<TIM, FREQ> {
662 pub fn new(tim: TIM, rcc: &mut Rcc) -> Self {
664 TIM::enable(rcc);
666 TIM::reset(rcc);
667
668 let mut t = Self { tim };
669 t.configure(&rcc.clocks);
670 t
671 }
672
673 pub fn configure(&mut self, clocks: &Clocks) {
675 let clk = TIM::timer_clock(clocks);
676 assert!(clk.raw() % FREQ == 0);
677 let psc = clk.raw() / FREQ;
678 self.tim.set_prescaler(u16::try_from(psc - 1).unwrap());
679 }
680
681 pub fn counter(self) -> Counter<TIM, FREQ> {
683 Counter(self)
684 }
685
686 pub fn delay(self) -> Delay<TIM, FREQ> {
688 Delay(self)
689 }
690
691 pub fn release(self) -> TIM {
693 self.tim
694 }
695
696 pub fn listen(&mut self, event: Event) {
701 self.tim.listen_interrupt(event, true);
702 }
703
704 pub fn clear_interrupt(&mut self, event: Event) {
709 self.tim.clear_interrupt_flag(event);
710 }
711
712 pub fn get_interrupt(&mut self) -> Event {
713 self.tim.get_interrupt_flag()
714 }
715
716 pub fn unlisten(&mut self, event: Event) {
718 self.tim.listen_interrupt(event, false);
719 }
720
721 pub fn stop_in_debug(&mut self, dbg: &mut DBG, state: bool) {
723 self.tim.stop_in_debug(dbg, state);
724 }
725}
726
727impl<TIM: Instance + MasterTimer, const FREQ: u32> FTimer<TIM, FREQ> {
728 pub fn set_master_mode(&mut self, mode: TIM::Mms) {
729 self.tim.master_mode(mode)
730 }
731}
732
733#[inline(always)]
734const fn compute_arr_presc(freq: u32, clock: u32) -> (u16, u32) {
735 let ticks = clock / freq;
736 let psc = (ticks - 1) / (1 << 16);
737 let arr = ticks / (psc + 1) - 1;
738 (psc as u16, arr)
739}
740
741hal!(
742 pac::TIM2: [Timer2, u16, dbg_tim2_stop, c: (CH4), m: tim2,],
743 pac::TIM3: [Timer3, u16, dbg_tim3_stop, c: (CH4), m: tim2,],
744);
745
746#[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity"))]
747hal!(
748 pac::TIM1: [Timer1, u16, dbg_tim1_stop, c: (CH4, _aoe), m: tim1,],
749);
750
751#[cfg(any(feature = "stm32f100", feature = "high", feature = "connectivity"))]
752hal! {
753 pac::TIM6: [Timer6, u16, dbg_tim6_stop, m: tim6,],
754}
755
756#[cfg(any(
757 all(feature = "high", any(feature = "stm32f101", feature = "stm32f103")),
758 any(feature = "stm32f100", feature = "connectivity")
759))]
760hal! {
761 pac::TIM7: [Timer7, u16, dbg_tim7_stop, m: tim6,],
762}
763
764#[cfg(feature = "stm32f100")]
765hal! {
766 pac::TIM15: [Timer15, u16, dbg_tim15_stop, c: (CH2),],
767 pac::TIM16: [Timer16, u16, dbg_tim16_stop, c: (CH1),],
768 pac::TIM17: [Timer17, u16, dbg_tim17_stop, c: (CH1),],
769}
770
771#[cfg(feature = "medium")]
772hal! {
773 pac::TIM4: [Timer4, u16, dbg_tim4_stop, c: (CH4), m: tim2,],
774}
775
776#[cfg(any(feature = "high", feature = "connectivity"))]
777hal! {
778 pac::TIM5: [Timer5, u16, dbg_tim5_stop, c: (CH4), m: tim2,],
779}
780
781#[cfg(all(feature = "stm32f103", feature = "high"))]
782hal! {
783 pac::TIM8: [Timer8, u16, dbg_tim8_stop, c: (CH4, _aoe), m: tim1,],
784}
785
786