Skip to main content

ch32_hal/timer/
complementary_pwm.rs

1//! PWM driver with complementary output support.
2
3use core::marker::PhantomData;
4
5use super::low_level::{CountingMode, OutputPolarity, Timer};
6use super::simple_pwm::{Ch1, Ch2, Ch3, Ch4, PwmPin};
7use super::{AdvancedInstance, Channel, Channel1ComplementaryPin, Channel2ComplementaryPin, Channel3ComplementaryPin};
8use crate::gpio::{AfType, AnyPin, OutputType, Speed};
9use crate::pac::timer::vals::Ckd;
10use crate::time::Hertz;
11use crate::timer::low_level::OutputCompareMode;
12use crate::Peri;
13
14/// Complementary PWM pin wrapper.
15///
16/// This wraps a pin to make it usable with PWM.
17pub struct ComplementaryPwmPin<'d, T, C> {
18    _pin: Peri<'d, AnyPin>,
19    phantom: PhantomData<(T, C)>,
20}
21
22macro_rules! complementary_channel_impl {
23    ($new_chx:ident, $channel:ident, $pin_trait:ident) => {
24        impl<'d, T: AdvancedInstance> ComplementaryPwmPin<'d, T, $channel> {
25            #[doc = concat!("Create a new ", stringify!($channel), " complementary PWM pin instance.")]
26            pub fn $new_chx<#[cfg(not(afio_h4))] const REMAP: u8>(
27                pin: Peri<'d, if_remap!(impl $pin_trait<T, REMAP>)>,
28            ) -> Self {
29                apply_remap!();
30                critical_section::with(|_| {
31                    pin.set_low();
32                    set_as_af!(pin, AfType::output(OutputType::PushPull, Speed::High));
33                });
34                ComplementaryPwmPin {
35                    _pin: pin.into(),
36                    phantom: PhantomData,
37                }
38            }
39        }
40    };
41}
42
43complementary_channel_impl!(new_ch1, Ch1, Channel1ComplementaryPin);
44complementary_channel_impl!(new_ch2, Ch2, Channel2ComplementaryPin);
45complementary_channel_impl!(new_ch3, Ch3, Channel3ComplementaryPin);
46
47/// PWM driver with support for standard and complementary outputs.
48pub struct ComplementaryPwm<'d, T: AdvancedInstance> {
49    inner: Timer<'d, T>,
50}
51
52impl<'d, T: AdvancedInstance> ComplementaryPwm<'d, T> {
53    /// Create a new complementary PWM driver.
54    #[allow(clippy::too_many_arguments)]
55    pub fn new(
56        tim: Peri<'d, T>,
57        _ch1: Option<PwmPin<'d, T, Ch1>>,
58        _ch1n: Option<ComplementaryPwmPin<'d, T, Ch1>>,
59        _ch2: Option<PwmPin<'d, T, Ch2>>,
60        _ch2n: Option<ComplementaryPwmPin<'d, T, Ch2>>,
61        _ch3: Option<PwmPin<'d, T, Ch3>>,
62        _ch3n: Option<ComplementaryPwmPin<'d, T, Ch3>>,
63        _ch4: Option<PwmPin<'d, T, Ch4>>,
64        // no complementary channel 4
65        // _ch4n: Option<ComplementaryPwmPin<'d, T, Ch4>>,
66        freq: Hertz,
67        counting_mode: CountingMode,
68    ) -> Self {
69        Self::new_inner(tim, freq, counting_mode)
70    }
71
72    fn new_inner(tim: Peri<'d, T>, freq: Hertz, counting_mode: CountingMode) -> Self {
73        let mut this = Self { inner: Timer::new(tim) };
74
75        this.inner.set_counting_mode(counting_mode);
76        this.set_frequency(freq);
77        this.inner.start();
78
79        this.inner.enable_outputs();
80
81        [Channel::Ch1, Channel::Ch2, Channel::Ch3].iter().for_each(|&channel| {
82            this.inner.set_output_compare_mode(channel, OutputCompareMode::PwmMode1);
83            this.inner.set_output_compare_preload(channel, true);
84        });
85        // no complementary channel 4
86        this.inner
87            .set_output_compare_mode(Channel::Ch4, OutputCompareMode::PwmMode1);
88
89        this
90    }
91
92    /// Enable the given channel.
93    pub fn enable(&mut self, channel: Channel) {
94        self.inner.enable_channel(channel, true);
95        if channel != Channel::Ch4 {
96            self.inner.enable_complementary_channel(channel, true);
97        }
98    }
99
100    /// Disable the given channel.
101    pub fn disable(&mut self, channel: Channel) {
102        self.inner.enable_channel(channel, false);
103        if channel != Channel::Ch4 {
104            self.inner.enable_complementary_channel(channel, false);
105        }
106    }
107
108    /// Set PWM frequency.
109    ///
110    /// Note: when you call this, the max duty value changes, so you will have to
111    /// call `set_duty` on all channels with the duty calculated based on the new max duty.
112    pub fn set_frequency(&mut self, freq: Hertz) {
113        self.inner.set_pwm_frequency(freq);
114    }
115
116    /// Get max duty value.
117    ///
118    /// This value depends on the configured frequency and the timer's clock rate from RCC.
119    pub fn get_max_duty(&self) -> u16 {
120        self.inner.get_max_pwm_duty().try_into().unwrap()
121    }
122
123    /// Set the duty for a given channel.
124    ///
125    /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included.
126    pub fn set_duty(&mut self, channel: Channel, duty: u16) {
127        assert!(duty <= self.get_max_duty());
128        self.inner.set_compare_value(channel, duty as _)
129    }
130
131    /// Set the output polarity for a given channel.
132    pub fn set_polarity(&mut self, channel: Channel, polarity: OutputPolarity) {
133        self.inner.set_output_polarity(channel, polarity);
134        self.inner.set_complementary_output_polarity(channel, polarity);
135    }
136
137    /// Set dead time in timer input clock ticks, rounded down to a supported value.
138    ///
139    /// Values above the hardware maximum are clamped to 4032 ticks.
140    pub fn set_dead_time(&mut self, value: u16) {
141        let (ckd, value) = compute_dead_time_value(value);
142
143        self.inner.set_dead_time_clock_division(ckd);
144        self.inner.set_dead_time_value(value);
145    }
146}
147
148fn compute_dead_time_value(value: u16) -> (Ckd, u8) {
149    /*
150        Dead-time = T_clk * T_dts * T_dtg
151
152        T_dts:
153        This bit-field indicates the division ratio between the timer clock (CK_INT) frequency and the
154        dead-time and sampling clock (tDTS)used by the dead-time generators and the digital filters
155        (ETR, TIx),
156        00: tDTS=tCK_INT
157        01: tDTS=2*tCK_INT
158        10: tDTS=4*tCK_INT
159
160        T_dtg:
161        This bit-field defines the duration of the dead-time inserted between the complementary
162        outputs. DT correspond to this duration.
163        DTG[7:5]=0xx => DT=DTG[7:0]x tdtg with tdtg=tDTS.
164        DTG[7:5]=10x => DT=(64+DTG[5:0])xtdtg with Tdtg=2xtDTS.
165        DTG[7:5]=110 => DT=(32+DTG[4:0])xtdtg with Tdtg=8xtDTS.
166        DTG[7:5]=111 => DT=(32+DTG[4:0])xtdtg with Tdtg=16xtDTS.
167        Example if TDTS=125ns (8MHz), dead-time possible values are:
168        0 to 15875 ns by 125 ns steps,
169        16 us to 31750 ns by 250 ns steps,
170        32 us to 63us by 1 us steps,
171        64 us to 126 us by 2 us steps
172    */
173
174    let mut error = u16::MAX;
175    let mut ckd = Ckd::DIV_1;
176    let mut bits = 0u8;
177
178    for this_ckd in [Ckd::DIV_1, Ckd::DIV_2, Ckd::DIV_4] {
179        let outdiv = match this_ckd {
180            Ckd::DIV_1 => 1,
181            Ckd::DIV_2 => 2,
182            Ckd::DIV_4 => 4,
183            _ => unreachable!(),
184        };
185
186        // 127
187        // 128
188        // ..
189        // 254
190        // 256
191        // ..
192        // 504
193        // 512
194        // ..
195        // 1008
196
197        let target = value / outdiv;
198        let (these_bits, result) = if target < 128 {
199            (target as u8, target)
200        } else if target < 256 {
201            (64 + (target / 2) as u8, (target - target % 2))
202        } else if target < 512 {
203            (0xc0 | ((target / 8) as u8 - 32), (target - target % 8))
204        } else if target < 1008 {
205            (0xe0 | ((target / 16) as u8 - 32), (target - target % 16))
206        } else {
207            (u8::MAX, 1008)
208        };
209
210        let this_error = value.abs_diff(result * outdiv);
211        if error > this_error {
212            ckd = this_ckd;
213            bits = these_bits;
214            error = this_error;
215        }
216
217        if error == 0 {
218            break;
219        }
220    }
221
222    (ckd, bits)
223}