esp-hal 1.2.0

Bare-metal HAL for Espressif devices
Documentation
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! # LEDC channel
//!
//! ## Overview
//! The LEDC Channel module  provides a high-level interface to
//! configure and control individual PWM channels of the LEDC peripheral.
//!
//! ## Configuration
//! The module allows precise and flexible control over LED lighting and other
//! `Pulse-Width Modulation (PWM)` applications by offering configurable duty
//! cycles and frequencies.

use super::{
    low_level,
    timer::{TimerIFace, TimerSpeed},
};
use crate::{
    gpio::{
        DriveMode,
        OutputConfig,
        interconnect::{self, PeripheralOutput},
    },
    pac::ledc::RegisterBlock,
    peripherals::LEDC,
};

/// Fade parameter sub-errors
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum FadeError {
    /// Starts duty % out of range.
    StartDuty,
    /// Ends duty % out of range.
    EndDuty,
    /// Duty % change from start to end is out of range.
    DutyRange,
    /// Duration too long for timer frequency and duty resolution
    Duration,
}

/// Channel errors
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
    /// Invalid duty % value
    Duty,
    /// Timer not configured
    Timer,
    /// Channel not configured
    Channel,
    /// Fade parameters invalid
    Fade(FadeError),
}

/// Channel number
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Number {
    /// Channel 0
    Channel0 = 0,
    /// Channel 1
    Channel1 = 1,
    /// Channel 2
    Channel2 = 2,
    /// Channel 3
    Channel3 = 3,
    /// Channel 4
    Channel4 = 4,
    /// Channel 5
    Channel5 = 5,
    #[cfg(ledc_channel_count = "8")]
    /// Channel 6
    Channel6 = 6,
    #[cfg(ledc_channel_count = "8")]
    /// Channel 7
    Channel7 = 7,
}

/// Channel configuration
pub mod config {
    use crate::{
        gpio::DriveMode,
        ledc::timer::{TimerIFace, TimerSpeed},
    };

    /// Channel configuration
    #[derive(Copy, Clone)]
    pub struct Config<'a, S: TimerSpeed> {
        /// A reference to the timer associated with this channel.
        pub timer: &'a dyn TimerIFace<S>,
        /// The duty cycle percentage (0-100).
        pub duty_pct: u8,
        /// The pin configuration (PushPull or OpenDrain).
        pub drive_mode: DriveMode,
    }
}

/// Channel interface
pub trait ChannelIFace<'a, S: TimerSpeed + 'a>
where
    Channel<'a, S>: ChannelHW,
{
    /// Configures channel.
    fn configure(&mut self, config: config::Config<'a, S>) -> Result<(), Error>;

    /// Sets channel duty HW.
    fn set_duty(&self, duty_pct: u8) -> Result<(), Error>;

    /// Starts a duty-cycle fade.
    fn start_duty_fade(
        &self,
        start_duty_pct: u8,
        end_duty_pct: u8,
        duration_ms: u16,
    ) -> Result<(), Error>;

    /// Returns whether a duty-cycle fade is running.
    fn is_duty_fade_running(&self) -> bool;
}

/// Channel HW interface
pub trait ChannelHW {
    /// Configures Channel HW except for the duty which is set via
    /// [`Self::set_duty_hw`].
    fn configure_hw(&mut self) -> Result<(), Error>;
    /// Configures the hardware for the channel with a specific pin
    /// configuration.
    fn configure_hw_with_drive_mode(&mut self, cfg: DriveMode) -> Result<(), Error>;

    /// Sets channel duty HW.
    fn set_duty_hw(&self, duty: u32);

    /// Starts a duty-cycle fade HW.
    fn start_duty_fade_hw(
        &self,
        start_duty: u32,
        duty_inc: bool,
        duty_steps: u16,
        cycles_per_step: u16,
        duty_per_cycle: u16,
    );

    /// Returns whether a duty-cycle fade is running HW.
    fn is_duty_fade_running_hw(&self) -> bool;
}

/// Channel struct
pub struct Channel<'a, S: TimerSpeed> {
    ledc: &'a RegisterBlock,
    timer: Option<&'a dyn TimerIFace<S>>,
    number: Number,
    output_pin: interconnect::OutputSignal<'a>,
}

impl<'a, S: TimerSpeed> Channel<'a, S> {
    /// Returns a new channel.
    pub fn new(number: Number, output_pin: impl PeripheralOutput<'a>) -> Self {
        let ledc = LEDC::regs();
        Channel {
            ledc,
            timer: None,
            number,
            output_pin: output_pin.into(),
        }
    }
}

impl<'a, S: TimerSpeed> ChannelIFace<'a, S> for Channel<'a, S>
where
    Channel<'a, S>: ChannelHW,
{
    /// Configures channel.
    fn configure(&mut self, config: config::Config<'a, S>) -> Result<(), Error> {
        self.timer = Some(config.timer);

        self.set_duty(config.duty_pct)?;
        self.configure_hw_with_drive_mode(config.drive_mode)?;

        Ok(())
    }

    /// Sets duty % of channel.
    fn set_duty(&self, duty_pct: u8) -> Result<(), Error> {
        let duty_exp;
        if let Some(timer) = self.timer {
            if let Some(timer_duty) = timer.duty() {
                duty_exp = timer_duty as u32;
            } else {
                return Err(Error::Timer);
            }
        } else {
            return Err(Error::Channel);
        }

        let duty_range = 2u32.pow(duty_exp);
        let duty_value = (duty_range * duty_pct as u32) / 100;

        if duty_pct > 100u8 {
            // duty_pct greater than 100%
            return Err(Error::Duty);
        }

        self.set_duty_hw(duty_value);

        Ok(())
    }

    /// Starts a duty fade from one % to another.
    ///
    /// There is a constraint on the combination of timer frequency, timer PWM
    /// duty resolution (the bit count), the fade "range" (abs(start-end)), and
    /// the duration:
    ///
    /// frequency * duration / ((1<<bit_count) * abs(start-end)) < 1024
    ///
    /// Small percentage changes, long durations, coarse PWM resolutions (that
    /// is, low bit counts), and high timer frequencies will all be more likely
    /// to fail this requirement. If it does fail, returns an error.
    fn start_duty_fade(
        &self,
        start_duty_pct: u8,
        end_duty_pct: u8,
        duration_ms: u16,
    ) -> Result<(), Error> {
        let duty_exp;
        let frequency;
        if start_duty_pct > 100u8 {
            return Err(Error::Fade(FadeError::StartDuty));
        }
        if end_duty_pct > 100u8 {
            return Err(Error::Fade(FadeError::EndDuty));
        }
        if let Some(timer) = self.timer {
            if let Some(timer_duty) = timer.duty() {
                if timer.frequency() > 0 {
                    duty_exp = timer_duty as u32;
                    frequency = timer.frequency();
                } else {
                    return Err(Error::Timer);
                }
            } else {
                return Err(Error::Timer);
            }
        } else {
            return Err(Error::Channel);
        }

        let duty_range = (1u32 << duty_exp) - 1;
        let start_duty_value = (duty_range * start_duty_pct as u32) / 100;
        let end_duty_value = (duty_range * end_duty_pct as u32) / 100;

        // NB: since we do the multiplication first here, there's no loss of
        // precision from using milliseconds instead of (e.g.) nanoseconds.
        let pwm_cycles = (duration_ms as u32) * frequency / 1000;

        let abs_duty_diff = end_duty_value.abs_diff(start_duty_value);
        let duty_steps: u32 = u16::try_from(abs_duty_diff).unwrap_or(65535).into();
        // This conversion may fail if duration_ms is too big, and if either
        // duty_steps gets truncated, or the fade is over a short range of duty
        // percentages, so it's too small.  Returning an Err in either case is
        // fine: shortening the duration_ms will sort things out.
        let cycles_per_step: u16 = (pwm_cycles / duty_steps)
            .try_into()
            .map_err(|_| Error::Fade(FadeError::Duration))
            .and_then(|res| {
                if res > 1023 {
                    Err(Error::Fade(FadeError::Duration))
                } else {
                    Ok(res)
                }
            })?;
        // This can't fail unless abs_duty_diff is bigger than 65536*65535-1,
        // and so duty_steps gets truncated.  But that requires duty_exp to be
        // at least 32, and the hardware only supports up to 20.  Still, handle
        // it in case something changes in the future.
        let duty_per_cycle: u16 = (abs_duty_diff / duty_steps)
            .try_into()
            .map_err(|_| Error::Fade(FadeError::DutyRange))?;

        self.start_duty_fade_hw(
            start_duty_value,
            end_duty_value > start_duty_value,
            duty_steps.try_into().unwrap(),
            cycles_per_step,
            duty_per_cycle,
        );

        Ok(())
    }

    fn is_duty_fade_running(&self) -> bool {
        self.is_duty_fade_running_hw()
    }
}

mod ehal1 {
    use embedded_hal::pwm::{self, ErrorKind, ErrorType, SetDutyCycle};

    use super::{Channel, ChannelHW, Error};
    use crate::ledc::timer::TimerSpeed;

    impl pwm::Error for Error {
        fn kind(&self) -> pwm::ErrorKind {
            ErrorKind::Other
        }
    }

    impl<S: TimerSpeed> ErrorType for Channel<'_, S> {
        type Error = Error;
    }

    impl<'a, S: TimerSpeed> SetDutyCycle for Channel<'a, S>
    where
        Channel<'a, S>: ChannelHW,
    {
        fn max_duty_cycle(&self) -> u16 {
            let duty_exp;

            if let Some(timer_duty) = self.timer.and_then(|timer| timer.duty()) {
                duty_exp = timer_duty as u32;
            } else {
                return 0;
            }

            let duty_range = 2u32.pow(duty_exp);

            duty_range as u16
        }

        fn set_duty_cycle(&mut self, mut duty: u16) -> Result<(), Self::Error> {
            let max = self.max_duty_cycle();
            duty = if duty > max { max } else { duty };
            self.set_duty_hw(duty.into());
            Ok(())
        }
    }
}

impl<S: crate::ledc::timer::TimerSpeed> Channel<'_, S> {
    fn set_channel(&mut self, timer_number: u8) {
        low_level::set_channel(self.ledc, self.number, timer_number, S::IS_HS);
        low_level::start_duty_without_fading(self.ledc, self.number, S::IS_HS);
    }

    fn start_duty_without_fading(&self) {
        low_level::start_duty_without_fading(self.ledc, self.number, S::IS_HS);
    }

    fn update_channel(&self) {
        low_level::update_channel(self.ledc, self.number, S::IS_HS);
    }
}

impl<S> ChannelHW for Channel<'_, S>
where
    S: crate::ledc::timer::TimerSpeed,
{
    /// Configures Channel HW.
    fn configure_hw(&mut self) -> Result<(), Error> {
        self.configure_hw_with_drive_mode(DriveMode::PushPull)
    }

    fn configure_hw_with_drive_mode(&mut self, cfg: DriveMode) -> Result<(), Error> {
        if let Some(timer) = self.timer {
            if !timer.is_configured() {
                return Err(Error::Timer);
            }

            self.output_pin
                .apply_output_config(&OutputConfig::default().with_drive_mode(cfg));
            self.output_pin.set_output_enable(true);

            let timer_number = timer.number() as u8;

            self.set_channel(timer_number);
            self.update_channel();

            let signal = low_level::output_signal(self.number, S::IS_HS);
            signal.connect_to(&self.output_pin);
        } else {
            return Err(Error::Timer);
        }

        Ok(())
    }

    /// Sets duty in channel HW.
    fn set_duty_hw(&self, duty: u32) {
        low_level::set_duty_hw(self.ledc, self.number, S::IS_HS, duty);
        self.start_duty_without_fading();
        self.update_channel();
    }

    /// Starts a duty-cycle fade HW.
    fn start_duty_fade_hw(
        &self,
        start_duty: u32,
        duty_inc: bool,
        duty_steps: u16,
        cycles_per_step: u16,
        duty_per_cycle: u16,
    ) {
        low_level::start_duty_fade_hw(
            self.ledc,
            self.number,
            S::IS_HS,
            start_duty,
            duty_inc,
            duty_steps,
            cycles_per_step,
            duty_per_cycle,
        );
        self.update_channel();
    }

    fn is_duty_fade_running_hw(&self) -> bool {
        low_level::is_duty_fade_running_hw(self.ledc, self.number, S::IS_HS)
    }
}