Skip to main content

esp_hal/ledc/
timer.rs

1//! # LEDC timer
2//!
3//! ## Overview
4//! The LEDC Timer provides a high-level interface to configure and control
5//! individual timers of the `LEDC` peripheral.
6//!
7//! ## Configuration
8//! The module allows precise and flexible control over timer configurations,
9//! duty cycles and frequencies, making it ideal for Pulse-Width Modulation
10//! (PWM) applications and LED lighting control.
11
12#[cfg(ledc_version = "1")]
13use super::HighSpeed;
14use super::{LowSpeed, Speed, low_level};
15use crate::{pac, time::Rate};
16
17const LEDC_TIMER_DIV_NUM_MAX: u64 = 0x3FFFF;
18
19/// Timer errors
20#[derive(Debug, Clone, Copy, PartialEq)]
21#[cfg_attr(feature = "defmt", derive(defmt::Format))]
22pub enum Error {
23    /// Invalid Divisor
24    Divisor,
25    /// Frequency unset
26    FrequencyUnset,
27}
28
29#[cfg(ledc_version = "1")]
30/// Clock source for HS Timers.
31#[derive(PartialEq, Eq, Copy, Clone, Debug)]
32#[cfg_attr(feature = "defmt", derive(defmt::Format))]
33pub enum HSClockSource {
34    /// APB clock.
35    APBClk,
36    // TODO RefTick,
37}
38
39/// Clock source for LS Timers.
40#[derive(PartialEq, Eq, Copy, Clone, Debug)]
41#[cfg_attr(feature = "defmt", derive(defmt::Format))]
42pub enum LSClockSource {
43    /// APB clock.
44    APBClk,
45    // TODO SLOWClk
46}
47
48/// Timer number
49#[derive(PartialEq, Eq, Copy, Clone, Debug)]
50#[cfg_attr(feature = "defmt", derive(defmt::Format))]
51pub enum Number {
52    /// Timer 0.
53    Timer0 = 0,
54    /// Timer 1.
55    Timer1 = 1,
56    /// Timer 2.
57    Timer2 = 2,
58    /// Timer 3.
59    Timer3 = 3,
60}
61
62/// Timer configuration
63pub mod config {
64    use crate::time::Rate;
65
66    /// Number of bits reserved for duty cycle adjustment
67    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
68    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
69    #[allow(clippy::enum_variant_names)] // FIXME: resolve before stabilizing this driver
70    pub enum Duty {
71        /// 1-bit resolution for duty cycle adjustment.
72        Duty1Bit = 1,
73        /// 2-bit resolution for duty cycle adjustment.
74        Duty2Bit,
75        /// 3-bit resolution for duty cycle adjustment.
76        Duty3Bit,
77        /// 4-bit resolution for duty cycle adjustment.
78        Duty4Bit,
79        /// 5-bit resolution for duty cycle adjustment.
80        Duty5Bit,
81        /// 6-bit resolution for duty cycle adjustment.
82        Duty6Bit,
83        /// 7-bit resolution for duty cycle adjustment.
84        Duty7Bit,
85        /// 8-bit resolution for duty cycle adjustment.
86        Duty8Bit,
87        /// 9-bit resolution for duty cycle adjustment.
88        Duty9Bit,
89        /// 10-bit resolution for duty cycle adjustment.
90        Duty10Bit,
91        /// 11-bit resolution for duty cycle adjustment.
92        Duty11Bit,
93        /// 12-bit resolution for duty cycle adjustment.
94        Duty12Bit,
95        /// 13-bit resolution for duty cycle adjustment.
96        Duty13Bit,
97        /// 14-bit resolution for duty cycle adjustment.
98        Duty14Bit,
99        #[cfg(ledc_version = "1")]
100        /// 15-bit resolution for duty cycle adjustment.
101        Duty15Bit,
102        #[cfg(ledc_version = "1")]
103        /// 16-bit resolution for duty cycle adjustment.
104        Duty16Bit,
105        #[cfg(ledc_version = "1")]
106        /// 17-bit resolution for duty cycle adjustment.
107        Duty17Bit,
108        #[cfg(ledc_version = "1")]
109        /// 18-bit resolution for duty cycle adjustment.
110        Duty18Bit,
111        #[cfg(ledc_version = "1")]
112        /// 19-bit resolution for duty cycle adjustment.
113        Duty19Bit,
114        #[cfg(ledc_version = "1")]
115        /// 20-bit resolution for duty cycle adjustment.
116        Duty20Bit,
117    }
118
119    impl TryFrom<u32> for Duty {
120        type Error = ();
121
122        fn try_from(value: u32) -> Result<Self, Self::Error> {
123            Ok(match value {
124                1 => Self::Duty1Bit,
125                2 => Self::Duty2Bit,
126                3 => Self::Duty3Bit,
127                4 => Self::Duty4Bit,
128                5 => Self::Duty5Bit,
129                6 => Self::Duty6Bit,
130                7 => Self::Duty7Bit,
131                8 => Self::Duty8Bit,
132                9 => Self::Duty9Bit,
133                10 => Self::Duty10Bit,
134                11 => Self::Duty11Bit,
135                12 => Self::Duty12Bit,
136                13 => Self::Duty13Bit,
137                14 => Self::Duty14Bit,
138                #[cfg(ledc_version = "1")]
139                15 => Self::Duty15Bit,
140                #[cfg(ledc_version = "1")]
141                16 => Self::Duty16Bit,
142                #[cfg(ledc_version = "1")]
143                17 => Self::Duty17Bit,
144                #[cfg(ledc_version = "1")]
145                18 => Self::Duty18Bit,
146                #[cfg(ledc_version = "1")]
147                19 => Self::Duty19Bit,
148                #[cfg(ledc_version = "1")]
149                20 => Self::Duty20Bit,
150                _ => Err(())?,
151            })
152        }
153    }
154
155    /// Timer configuration
156    #[derive(Copy, Clone)]
157    pub struct Config<CS> {
158        /// The duty cycle resolution.
159        pub duty: Duty,
160        /// The clock source for the timer.
161        pub clock_source: CS,
162        /// The frequency of the PWM signal in Hertz.
163        pub frequency: Rate,
164    }
165}
166
167/// Trait defining the type of timer source
168pub trait TimerSpeed: Speed {
169    /// The type of clock source used by the timer in this speed mode.
170    type ClockSourceType;
171}
172
173/// Timer source type for LowSpeed timers
174impl TimerSpeed for LowSpeed {
175    /// The clock source type for low-speed timers.
176    type ClockSourceType = LSClockSource;
177}
178
179#[cfg(ledc_version = "1")]
180/// Timer source type for HighSpeed timers
181impl TimerSpeed for HighSpeed {
182    /// The clock source type for high-speed timers.
183    type ClockSourceType = HSClockSource;
184}
185
186/// Interface for Timers
187pub trait TimerIFace<S: TimerSpeed> {
188    /// Returns the frequency of the timer.
189    fn freq(&self) -> Option<Rate>;
190
191    /// Configures the timer.
192    fn configure(&mut self, config: config::Config<S::ClockSourceType>) -> Result<(), Error>;
193
194    /// Returns whether the timer has been configured.
195    fn is_configured(&self) -> bool;
196
197    /// Returns the duty resolution of the timer.
198    fn duty(&self) -> Option<config::Duty>;
199
200    /// Returns the timer number.
201    fn number(&self) -> Number;
202
203    /// Returns the timer frequency, or 0 if not configured.
204    fn frequency(&self) -> u32;
205}
206
207/// Interface for HW configuration of timer
208pub trait TimerHW<S: TimerSpeed> {
209    /// Returns the current source timer frequency from the HW.
210    fn freq_hw(&self) -> Option<Rate>;
211
212    /// Configures the HW for the timer.
213    fn configure_hw(&self, divisor: u32);
214
215    /// Updates the timer in HW.
216    fn update_hw(&self);
217}
218
219/// Timer struct
220pub struct Timer<'a, S: TimerSpeed> {
221    ledc: &'a pac::ledc::RegisterBlock,
222    number: Number,
223    duty: Option<config::Duty>,
224    frequency: u32,
225    configured: bool,
226    #[cfg(soc_has_clock_node_ref_tick)]
227    use_ref_tick: bool,
228    clock_source: Option<S::ClockSourceType>,
229}
230
231impl<'a, S: TimerSpeed> TimerIFace<S> for Timer<'a, S>
232where
233    Timer<'a, S>: TimerHW<S>,
234{
235    /// Returns the frequency of the timer.
236    fn freq(&self) -> Option<Rate> {
237        self.freq_hw()
238    }
239
240    /// Configures the timer.
241    fn configure(&mut self, config: config::Config<S::ClockSourceType>) -> Result<(), Error> {
242        self.duty = Some(config.duty);
243        self.clock_source = Some(config.clock_source);
244
245        let src_freq: u32 = self.freq().ok_or(Error::FrequencyUnset)?.as_hz();
246        let precision = 1 << config.duty as u32;
247        let frequency: u32 = config.frequency.as_hz();
248        self.frequency = frequency;
249
250        #[cfg_attr(not(soc_has_clock_node_ref_tick), expect(unused_mut))]
251        let mut divisor = ((src_freq as u64) << 8) / frequency as u64 / precision as u64;
252
253        #[cfg(soc_has_clock_node_ref_tick)]
254        if divisor > LEDC_TIMER_DIV_NUM_MAX {
255            // APB_CLK results in divisor which too high. Try using REF_TICK as clock
256            // source.
257            self.use_ref_tick = true;
258            divisor = (1_000_000u64 << 8) / frequency as u64 / precision as u64;
259        }
260
261        if !(256..=LEDC_TIMER_DIV_NUM_MAX).contains(&divisor) {
262            return Err(Error::Divisor);
263        }
264
265        self.configure_hw(divisor as u32);
266        self.update_hw();
267
268        self.configured = true;
269
270        Ok(())
271    }
272
273    /// Returns whether the timer has been configured.
274    fn is_configured(&self) -> bool {
275        self.configured
276    }
277
278    /// Returns the duty resolution of the timer.
279    fn duty(&self) -> Option<config::Duty> {
280        self.duty
281    }
282
283    /// Returns the timer number.
284    fn number(&self) -> Number {
285        self.number
286    }
287
288    /// Returns the timer frequency.
289    fn frequency(&self) -> u32 {
290        self.frequency
291    }
292}
293
294impl<'a, S: TimerSpeed> Timer<'a, S> {
295    /// Creates a new instance of a timer.
296    pub fn new(ledc: &'a pac::ledc::RegisterBlock, number: Number) -> Self {
297        Timer {
298            ledc,
299            number,
300            duty: None,
301            frequency: 0u32,
302            configured: false,
303            #[cfg(soc_has_clock_node_ref_tick)]
304            use_ref_tick: false,
305            clock_source: None,
306        }
307    }
308}
309
310/// Timer HW implementation for LowSpeed timers
311impl TimerHW<LowSpeed> for Timer<'_, LowSpeed> {
312    /// Returns the current source timer frequency from the HW.
313    fn freq_hw(&self) -> Option<Rate> {
314        self.clock_source.map(low_level::ls_freq_hw)
315    }
316
317    /// Configures the HW for the timer.
318    fn configure_hw(&self, divisor: u32) {
319        let duty = unwrap!(self.duty) as u8;
320        #[cfg(soc_has_clock_node_ref_tick)]
321        let use_ref_tick = self.use_ref_tick;
322        #[cfg(not(soc_has_clock_node_ref_tick))]
323        let use_ref_tick = false;
324        low_level::ls_configure_hw(self.ledc, self.number, divisor, duty, use_ref_tick);
325    }
326
327    /// Updates the timer in HW.
328    fn update_hw(&self) {
329        low_level::ls_update_hw(self.ledc, self.number);
330    }
331}
332
333#[cfg(ledc_version = "1")]
334/// Timer HW implementation for HighSpeed timers
335impl TimerHW<HighSpeed> for Timer<'_, HighSpeed> {
336    /// Returns the current source timer frequency from the HW.
337    fn freq_hw(&self) -> Option<Rate> {
338        self.clock_source.map(low_level::hs_freq_hw)
339    }
340
341    /// Configures the HW for the timer.
342    fn configure_hw(&self, divisor: u32) {
343        let duty = unwrap!(self.duty) as u8;
344        low_level::hs_configure_hw(
345            self.ledc,
346            self.number,
347            divisor,
348            duty,
349            unwrap!(self.clock_source),
350        );
351    }
352
353    /// Updates the timer in HW.
354    fn update_hw(&self) {
355        low_level::hs_update_hw();
356    }
357}