esp_hal/ledc/
timer.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! # LEDC timer
//!
//! ## Overview
//! The LEDC Timer provides a high-level interface to configure and control
//! individual timers of the `LEDC` peripheral.
//!
//! ## Configuration
//! The module allows precise and flexible control over timer configurations,
//! duty cycles and frequencies, making it ideal for Pulse-Width Modulation
//! (PWM) applications and LED lighting control.
//!
//! LEDC uses APB as clock source.

#[cfg(esp32)]
use super::HighSpeed;
use super::{LowSpeed, Speed};
use crate::{clock::Clocks, pac, time::Rate};

const LEDC_TIMER_DIV_NUM_MAX: u64 = 0x3FFFF;

/// Timer errors
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
    /// Invalid Divisor
    Divisor,
}

#[cfg(esp32)]
/// Clock source for HS Timers
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum HSClockSource {
    /// APB clock.
    APBClk,
    // TODO RefTick,
}

/// Clock source for LS Timers
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum LSClockSource {
    /// APB clock.
    APBClk,
    // TODO SLOWClk
}

/// Timer number
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Number {
    /// Timer 0.
    Timer0 = 0,
    /// Timer 1.
    Timer1 = 1,
    /// Timer 2.
    Timer2 = 2,
    /// Timer 3.
    Timer3 = 3,
}

/// Timer configuration
pub mod config {
    use crate::time::Rate;

    /// Number of bits reserved for duty cycle adjustment
    #[derive(PartialEq, Eq, Copy, Clone, Debug)]
    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
    #[allow(clippy::enum_variant_names)] // FIXME: resolve before stabilizing this driver
    pub enum Duty {
        /// 1-bit resolution for duty cycle adjustment.
        Duty1Bit = 1,
        /// 2-bit resolution for duty cycle adjustment.
        Duty2Bit,
        /// 3-bit resolution for duty cycle adjustment.
        Duty3Bit,
        /// 4-bit resolution for duty cycle adjustment.
        Duty4Bit,
        /// 5-bit resolution for duty cycle adjustment.
        Duty5Bit,
        /// 6-bit resolution for duty cycle adjustment.
        Duty6Bit,
        /// 7-bit resolution for duty cycle adjustment.
        Duty7Bit,
        /// 8-bit resolution for duty cycle adjustment.
        Duty8Bit,
        /// 9-bit resolution for duty cycle adjustment.
        Duty9Bit,
        /// 10-bit resolution for duty cycle adjustment.
        Duty10Bit,
        /// 11-bit resolution for duty cycle adjustment.
        Duty11Bit,
        /// 12-bit resolution for duty cycle adjustment.
        Duty12Bit,
        /// 13-bit resolution for duty cycle adjustment.
        Duty13Bit,
        /// 14-bit resolution for duty cycle adjustment.
        Duty14Bit,
        #[cfg(esp32)]
        /// 15-bit resolution for duty cycle adjustment.
        Duty15Bit,
        #[cfg(esp32)]
        /// 16-bit resolution for duty cycle adjustment.
        Duty16Bit,
        #[cfg(esp32)]
        /// 17-bit resolution for duty cycle adjustment.
        Duty17Bit,
        #[cfg(esp32)]
        /// 18-bit resolution for duty cycle adjustment.
        Duty18Bit,
        #[cfg(esp32)]
        /// 19-bit resolution for duty cycle adjustment.
        Duty19Bit,
        #[cfg(esp32)]
        /// 20-bit resolution for duty cycle adjustment.
        Duty20Bit,
    }

    impl TryFrom<u32> for Duty {
        type Error = ();

        fn try_from(value: u32) -> Result<Self, Self::Error> {
            Ok(match value {
                1 => Self::Duty1Bit,
                2 => Self::Duty2Bit,
                3 => Self::Duty3Bit,
                4 => Self::Duty4Bit,
                5 => Self::Duty5Bit,
                6 => Self::Duty6Bit,
                7 => Self::Duty7Bit,
                8 => Self::Duty8Bit,
                9 => Self::Duty9Bit,
                10 => Self::Duty10Bit,
                11 => Self::Duty11Bit,
                12 => Self::Duty12Bit,
                13 => Self::Duty13Bit,
                14 => Self::Duty14Bit,
                #[cfg(esp32)]
                15 => Self::Duty15Bit,
                #[cfg(esp32)]
                16 => Self::Duty16Bit,
                #[cfg(esp32)]
                17 => Self::Duty17Bit,
                #[cfg(esp32)]
                18 => Self::Duty18Bit,
                #[cfg(esp32)]
                19 => Self::Duty19Bit,
                #[cfg(esp32)]
                20 => Self::Duty20Bit,
                _ => Err(())?,
            })
        }
    }

    /// Timer configuration
    #[derive(Copy, Clone)]
    pub struct Config<CS> {
        /// The duty cycle resolution.
        pub duty: Duty,
        /// The clock source for the timer.
        pub clock_source: CS,
        /// The frequency of the PWM signal in Hertz.
        pub frequency: Rate,
    }
}

/// Trait defining the type of timer source
pub trait TimerSpeed: Speed {
    /// The type of clock source used by the timer in this speed mode.
    type ClockSourceType;
}

/// Timer source type for LowSpeed timers
impl TimerSpeed for LowSpeed {
    /// The clock source type for low-speed timers.
    type ClockSourceType = LSClockSource;
}

#[cfg(esp32)]
/// Timer source type for HighSpeed timers
impl TimerSpeed for HighSpeed {
    /// The clock source type for high-speed timers.
    type ClockSourceType = HSClockSource;
}

/// Interface for Timers
pub trait TimerIFace<S: TimerSpeed> {
    /// Return the frequency of the timer
    fn freq(&self) -> Option<Rate>;

    /// Configure the timer
    fn configure(&mut self, config: config::Config<S::ClockSourceType>) -> Result<(), Error>;

    /// Check if the timer has been configured
    fn is_configured(&self) -> bool;

    /// Return the duty resolution of the timer
    fn duty(&self) -> Option<config::Duty>;

    /// Return the timer number
    fn number(&self) -> Number;

    /// Return the timer frequency, or 0 if not configured
    fn frequency(&self) -> u32;
}

/// Interface for HW configuration of timer
pub trait TimerHW<S: TimerSpeed> {
    /// Get the current source timer frequency from the HW
    fn freq_hw(&self) -> Option<Rate>;

    /// Configure the HW for the timer
    fn configure_hw(&self, divisor: u32);

    /// Update the timer in HW
    fn update_hw(&self);
}

/// Timer struct
pub struct Timer<'a, S: TimerSpeed> {
    ledc: &'a pac::ledc::RegisterBlock,
    number: Number,
    duty: Option<config::Duty>,
    frequency: u32,
    configured: bool,
    use_ref_tick: bool,
    clock_source: Option<S::ClockSourceType>,
}

impl<'a, S: TimerSpeed> TimerIFace<S> for Timer<'a, S>
where
    Timer<'a, S>: TimerHW<S>,
{
    /// Return the frequency of the timer
    fn freq(&self) -> Option<Rate> {
        self.freq_hw()
    }

    /// Configure the timer
    fn configure(&mut self, config: config::Config<S::ClockSourceType>) -> Result<(), Error> {
        self.duty = Some(config.duty);
        self.clock_source = Some(config.clock_source);

        // TODO: we should return some error here if `unwrap()` fails
        let src_freq: u32 = self.freq().unwrap().as_hz();
        let precision = 1 << config.duty as u32;
        let frequency: u32 = config.frequency.as_hz();
        self.frequency = frequency;

        let mut divisor = ((src_freq as u64) << 8) / frequency as u64 / precision as u64;

        if divisor > LEDC_TIMER_DIV_NUM_MAX {
            // APB_CLK results in divisor which too high. Try using REF_TICK as clock
            // source.
            self.use_ref_tick = true;
            divisor = (1_000_000u64 << 8) / frequency as u64 / precision as u64;
        }

        if !(256..LEDC_TIMER_DIV_NUM_MAX).contains(&divisor) {
            return Err(Error::Divisor);
        }

        self.configure_hw(divisor as u32);
        self.update_hw();

        self.configured = true;

        Ok(())
    }

    /// Check if the timer has been configured
    fn is_configured(&self) -> bool {
        self.configured
    }

    /// Return the duty resolution of the timer
    fn duty(&self) -> Option<config::Duty> {
        self.duty
    }

    /// Return the timer number
    fn number(&self) -> Number {
        self.number
    }

    /// Return the timer frequency
    fn frequency(&self) -> u32 {
        self.frequency
    }
}

impl<'a, S: TimerSpeed> Timer<'a, S> {
    /// Create a new instance of a timer
    pub fn new(ledc: &'a pac::ledc::RegisterBlock, number: Number) -> Self {
        Timer {
            ledc,
            number,
            duty: None,
            frequency: 0u32,
            configured: false,
            use_ref_tick: false,
            clock_source: None,
        }
    }
}

/// Timer HW implementation for LowSpeed timers
impl TimerHW<LowSpeed> for Timer<'_, LowSpeed> {
    /// Get the current source timer frequency from the HW
    fn freq_hw(&self) -> Option<Rate> {
        self.clock_source.map(|source| match source {
            LSClockSource::APBClk => {
                let clocks = Clocks::get();
                clocks.apb_clock
            }
        })
    }

    #[cfg(esp32)]
    /// Configure the HW for the timer
    fn configure_hw(&self, divisor: u32) {
        let duty = unwrap!(self.duty) as u8;
        let use_apb = !self.use_ref_tick;

        self.ledc
            .lstimer(self.number as usize)
            .conf()
            .modify(|_, w| unsafe {
                w.tick_sel().bit(use_apb);
                w.rst().clear_bit();
                w.pause().clear_bit();
                w.div_num().bits(divisor);
                w.duty_res().bits(duty)
            });
    }

    #[cfg(not(esp32))]
    /// Configure the HW for the timer
    fn configure_hw(&self, divisor: u32) {
        let duty = unwrap!(self.duty) as u8;
        let use_ref_tick = self.use_ref_tick;

        self.ledc
            .timer(self.number as usize)
            .conf()
            .modify(|_, w| unsafe {
                w.tick_sel().bit(use_ref_tick);
                w.rst().clear_bit();
                w.pause().clear_bit();
                w.clk_div().bits(divisor);
                w.duty_res().bits(duty)
            });
    }

    /// Update the timer in HW
    fn update_hw(&self) {
        cfg_if::cfg_if! {
            if #[cfg(esp32)] {
                let tmr = self.ledc.lstimer(self.number as usize);
            } else {
                let tmr = self.ledc.timer(self.number as usize);
            }
        }

        tmr.conf().modify(|_, w| w.para_up().set_bit());
    }
}

#[cfg(esp32)]
/// Timer HW implementation for HighSpeed timers
impl TimerHW<HighSpeed> for Timer<'_, HighSpeed> {
    /// Get the current source timer frequency from the HW
    fn freq_hw(&self) -> Option<Rate> {
        self.clock_source.map(|source| match source {
            HSClockSource::APBClk => {
                let clocks = Clocks::get();
                clocks.apb_clock
            }
        })
    }

    /// Configure the HW for the timer
    fn configure_hw(&self, divisor: u32) {
        let duty = unwrap!(self.duty) as u8;
        let sel_hstimer = self.clock_source == Some(HSClockSource::APBClk);

        self.ledc
            .hstimer(self.number as usize)
            .conf()
            .modify(|_, w| unsafe {
                w.tick_sel().bit(sel_hstimer);
                w.rst().clear_bit();
                w.pause().clear_bit();
                w.div_num().bits(divisor);
                w.duty_res().bits(duty)
            });
    }

    /// Update the timer in HW
    fn update_hw(&self) {
        // Nothing to do for HS timers
    }
}