stm32f1_hal/common/timer/
pwm.rs1use super::*;
2use core::convert::Infallible;
3use embedded_hal::pwm::{ErrorType, SetDutyCycle};
4
5pub struct PwmTimer<TIM> {
6 tim: TIM,
7 clk: Hertz,
8}
9impl<TIM: TimerWithPwm> PwmTimer<TIM> {
10 pub fn new(tim: TIM, clk: Hertz) -> Self {
11 Self { tim, clk }
12 }
13
14 #[inline(always)]
15 pub fn start(&mut self) {
16 self.tim.start_pwm();
17 }
18
19 #[inline(always)]
20 pub fn stop(&mut self) {
21 self.tim.stop_pwm();
22 }
23
24 #[inline]
25 pub fn get_count_value(&self) -> u32 {
26 self.tim.read_count()
27 }
28
29 #[inline]
30 pub fn get_max_duty(&self) -> u32 {
31 self.tim.read_auto_reload().wrapping_add(1)
32 }
33
34 #[inline]
35 pub fn config_freq(&mut self, update_freq: Hertz) {
36 self.tim.config_freq(self.clk, update_freq);
37 }
38}
39
40macro_rules! pwm_channel {
43 ($name:ident, $Tim:ident, $ch:expr, $en:ident) => {
44 pub struct $name<TIM> {
45 tim: TIM,
46 }
47
48 impl<TIM> $name<TIM> {
49 pub fn new(tim: TIM) -> Self {
50 Self { tim }
51 }
52 }
53
54 impl<TIM: $Tim> ErrorType for $name<TIM> {
55 type Error = Infallible;
56 }
57
58 impl<TIM: $Tim> SetDutyCycle for $name<TIM> {
59 #[inline(always)]
60 fn max_duty_cycle(&self) -> u16 {
61 (self.tim.read_auto_reload() as u16).wrapping_add(1)
62 }
63
64 #[inline(always)]
65 fn set_duty_cycle(&mut self, duty: u16) -> Result<(), Self::Error> {
66 self.tim.set_ch1_cc_value(duty as u32);
67 Ok(())
68 }
69 }
70
71 impl<TIM: $Tim> PwmChannel for $name<TIM> {
72 #[inline(always)]
73 fn config(&mut self, mode: PwmMode, polarity: PwmPolarity) {
74 self.tim.preload_output_channel_in_mode($ch, mode.into());
75 self.tim.set_polarity($ch, polarity);
76 }
77
78 #[inline(always)]
79 fn set_enable(&mut self, en: bool) {
80 self.tim.$en(en);
81 }
82 }
83 };
84}
85pwm_channel!(PwmChannel1, TimerWithPwm1Ch, Channel::C1, enable_ch1);
86pwm_channel!(PwmChannel2, TimerWithPwm2Ch, Channel::C2, enable_ch2);
87pwm_channel!(PwmChannel3, TimerWithPwm3Ch, Channel::C3, enable_ch3);
88pwm_channel!(PwmChannel4, TimerWithPwm4Ch, Channel::C4, enable_ch4);