Skip to main content

ch32_hal/timer/
simple_pwm.rs

1//! Simple PWM driver.
2
3use core::marker::PhantomData;
4
5use super::low_level::{CountingMode, OutputCompareMode, OutputPolarity, Timer};
6use super::{Channel, Channel1Pin, Channel2Pin, Channel3Pin, Channel4Pin, GeneralInstance16bit};
7use crate::gpio::{AfType, AnyPin, OutputType, Speed};
8use crate::time::Hertz;
9use crate::Peri;
10
11/// Channel 1 marker type.
12pub enum Ch1 {}
13/// Channel 2 marker type.
14pub enum Ch2 {}
15/// Channel 3 marker type.
16pub enum Ch3 {}
17/// Channel 4 marker type.
18pub enum Ch4 {}
19
20/// PWM pin wrapper.
21///
22/// This wraps a pin to make it usable with PWM.
23pub struct PwmPin<'d, T, C> {
24    _pin: Peri<'d, AnyPin>,
25    phantom: PhantomData<(T, C)>,
26}
27
28macro_rules! channel_impl {
29    ($new_chx:ident, $channel:ident, $pin_trait:ident) => {
30        impl<'d, T: GeneralInstance16bit> PwmPin<'d, T, $channel> {
31            #[doc = concat!("Create a new ", stringify!($channel), " PWM pin instance.")]
32            pub fn $new_chx<#[cfg(not(afio_h4))] const REMAP: u8>(
33                pin: Peri<'d, if_remap!(impl $pin_trait<T, REMAP>)>,
34            ) -> Self {
35                apply_remap!();
36                critical_section::with(|_| {
37                    set_as_af!(pin, AfType::output(OutputType::PushPull, Speed::High));
38                });
39                PwmPin {
40                    _pin: pin.into(),
41                    phantom: PhantomData,
42                }
43            }
44        }
45    };
46}
47
48channel_impl!(new_ch1, Ch1, Channel1Pin);
49channel_impl!(new_ch2, Ch2, Channel2Pin);
50channel_impl!(new_ch3, Ch3, Channel3Pin);
51channel_impl!(new_ch4, Ch4, Channel4Pin);
52
53/// Simple PWM driver.
54pub struct SimplePwm<'d, T: GeneralInstance16bit> {
55    inner: Timer<'d, T>,
56}
57
58impl<'d, T: GeneralInstance16bit> SimplePwm<'d, T> {
59    /// Create a new simple PWM driver.
60    pub fn new(
61        tim: Peri<'d, T>,
62        _ch1: Option<PwmPin<'d, T, Ch1>>,
63        _ch2: Option<PwmPin<'d, T, Ch2>>,
64        _ch3: Option<PwmPin<'d, T, Ch3>>,
65        _ch4: Option<PwmPin<'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        #[cfg(not(timer_x0))]
76        this.inner.set_counting_mode(counting_mode);
77        #[cfg(timer_x0)] // accept default counting mode
78        assert_eq!(counting_mode, CountingMode::EdgeAlignedUp);
79
80        this.set_frequency(freq);
81
82        this.inner.enable_outputs(); // Required for advanced timers, see SealedGeneralInstance for details
83
84        this.inner.start();
85
86        [Channel::Ch1, Channel::Ch2, Channel::Ch3, Channel::Ch4]
87            .iter()
88            .for_each(|&channel| {
89                this.inner.set_output_compare_mode(channel, OutputCompareMode::PwmMode1);
90
91                this.inner.set_output_compare_preload(channel, true);
92            });
93
94        this
95    }
96
97    /// Enable the given channel.
98    pub fn enable(&mut self, channel: Channel) {
99        self.inner.enable_channel(channel, true);
100    }
101
102    /// Disable the given channel.
103    pub fn disable(&mut self, channel: Channel) {
104        self.inner.enable_channel(channel, false);
105    }
106
107    /// Check whether given channel is enabled
108    pub fn is_enabled(&self, channel: Channel) -> bool {
109        self.inner.get_channel_enable_state(channel)
110    }
111
112    /// Set PWM frequency.
113    ///
114    /// Note: when you call this, the max duty value changes, so you will have to
115    /// call `set_duty` on all channels with the duty calculated based on the new max duty.
116    pub fn set_frequency(&mut self, freq: Hertz) {
117        self.inner.set_pwm_frequency(freq);
118    }
119
120    /// Get max duty value.
121    ///
122    /// This value depends on the configured frequency and the timer's clock rate from RCC.
123    pub fn get_max_duty(&self) -> u32 {
124        self.inner.get_max_pwm_duty()
125    }
126
127    /// Set the duty for a given channel.
128    ///
129    /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included.
130    pub fn set_duty(&mut self, channel: Channel, duty: u32) {
131        assert!(duty <= self.get_max_duty());
132        self.inner.set_compare_value(channel, duty)
133    }
134
135    /// Get the duty for a given channel.
136    ///
137    /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included.
138    pub fn get_duty(&self, channel: Channel) -> u32 {
139        self.inner.get_compare_value(channel)
140    }
141
142    /// Set the output polarity for a given channel.
143    pub fn set_polarity(&mut self, channel: Channel, polarity: OutputPolarity) {
144        self.inner.set_output_polarity(channel, polarity);
145    }
146
147    /// Set the output compare mode for a given channel.
148    pub fn set_output_compare_mode(&mut self, channel: Channel, mode: OutputCompareMode) {
149        self.inner.set_output_compare_mode(channel, mode);
150    }
151
152    /// Generate a sequence of PWM waveform
153    ///
154    /// Note:
155    /// you will need to provide corresponding TIMx_UP DMA channel to use this method.
156    #[cfg(todo)]
157    pub async fn waveform_up(
158        &mut self,
159        dma: impl Peripheral<P = impl super::UpDma<T>>,
160        channel: Channel,
161        duty: &[u16],
162    ) {
163        into_ref!(dma);
164
165        #[allow(clippy::let_unit_value)] // eg. stm32f334
166        let req = dma.request();
167
168        let original_duty_state = self.get_duty(channel);
169        let original_enable_state = self.is_enabled(channel);
170        let original_update_dma_state = self.inner.get_update_dma_state();
171
172        if !original_update_dma_state {
173            self.inner.enable_update_dma(true);
174        }
175
176        if !original_enable_state {
177            self.enable(channel);
178        }
179
180        unsafe {
181            #[cfg(not(any(bdma, gpdma)))]
182            use crate::dma::{Burst, FifoThreshold};
183            use crate::dma::{Transfer, TransferOptions};
184
185            let dma_transfer_option = TransferOptions {
186                #[cfg(not(any(bdma, gpdma)))]
187                fifo_threshold: Some(FifoThreshold::Full),
188                #[cfg(not(any(bdma, gpdma)))]
189                mburst: Burst::Incr8,
190                ..Default::default()
191            };
192
193            Transfer::new_write(
194                &mut dma,
195                req,
196                duty,
197                self.inner.regs_1ch().ccr(channel.index()).as_ptr() as *mut _,
198                dma_transfer_option,
199            )
200            .await
201        };
202
203        // restore output compare state
204        if !original_enable_state {
205            self.disable(channel);
206        }
207
208        self.set_duty(channel, original_duty_state);
209
210        // Since DMA is closed before timer update event trigger DMA is turn off,
211        // this can almost always trigger a DMA FIFO error.
212        //
213        // optional TODO:
214        // clean FEIF after disable UDE
215        if !original_update_dma_state {
216            self.inner.enable_update_dma(false);
217        }
218    }
219}
220
221/*
222macro_rules! impl_waveform_chx {
223    ($fn_name:ident, $dma_ch:ident, $cc_ch:ident) => {
224        impl<'d, T: GeneralInstance16bit> SimplePwm<'d, T> {
225            /// Generate a sequence of PWM waveform
226            ///
227            /// Note:
228            /// you will need to provide corresponding TIMx_CHy DMA channel to use this method.
229            pub async fn $fn_name(&mut self, dma: impl Peripheral<P = impl super::$dma_ch<T>>, duty: &[u16]) {
230                use crate::pac::timer::vals::Ccds;
231
232                into_ref!(dma);
233
234                #[allow(clippy::let_unit_value)] // eg. stm32f334
235                let req = dma.request();
236
237                let cc_channel = Channel::$cc_ch;
238
239                let original_duty_state = self.get_duty(cc_channel);
240                let original_enable_state = self.is_enabled(cc_channel);
241                let original_cc_dma_on_update = self.inner.get_cc_dma_selection() == Ccds::ONUPDATE;
242                let original_cc_dma_enabled = self.inner.get_cc_dma_enable_state(cc_channel);
243
244                // redirect CC DMA request onto Update Event
245                if !original_cc_dma_on_update {
246                    self.inner.set_cc_dma_selection(Ccds::ONUPDATE)
247                }
248
249                if !original_cc_dma_enabled {
250                    self.inner.set_cc_dma_enable_state(cc_channel, true);
251                }
252
253                if !original_enable_state {
254                    self.enable(cc_channel);
255                }
256
257                unsafe {
258                    #[cfg(not(any(bdma, gpdma)))]
259                    use crate::dma::{Burst, FifoThreshold};
260                    use crate::dma::{Transfer, TransferOptions};
261
262                    let dma_transfer_option = TransferOptions {
263                        #[cfg(not(any(bdma, gpdma)))]
264                        fifo_threshold: Some(FifoThreshold::Full),
265                        #[cfg(not(any(bdma, gpdma)))]
266                        mburst: Burst::Incr8,
267                        ..Default::default()
268                    };
269
270                    Transfer::new_write(
271                        &mut dma,
272                        req,
273                        duty,
274                        self.inner.regs_gp16().ccr(cc_channel.index()).as_ptr() as *mut _,
275                        dma_transfer_option,
276                    )
277                    .await
278                };
279
280                // restore output compare state
281                if !original_enable_state {
282                    self.disable(cc_channel);
283                }
284
285                self.set_duty(cc_channel, original_duty_state);
286
287                // Since DMA is closed before timer Capture Compare Event trigger DMA is turn off,
288                // this can almost always trigger a DMA FIFO error.
289                //
290                // optional TODO:
291                // clean FEIF after disable UDE
292                if !original_cc_dma_enabled {
293                    self.inner.set_cc_dma_enable_state(cc_channel, false);
294                }
295
296                if !original_cc_dma_on_update {
297                    self.inner.set_cc_dma_selection(Ccds::ONCOMPARE)
298                }
299            }
300        }
301    };
302}
303
304impl_waveform_chx!(waveform_ch1, Ch1Dma, Ch1);
305impl_waveform_chx!(waveform_ch2, Ch2Dma, Ch2);
306impl_waveform_chx!(waveform_ch3, Ch3Dma, Ch3);
307impl_waveform_chx!(waveform_ch4, Ch4Dma, Ch4);
308*/