ra-hal 0.3.0

Hardware Abstraction Layer (HAL) for the Renesas RA family of MCUs.
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Pulse Width Modulation driver utilizing the General PWM Timer (`GPT`).
//!
//! # Notes
//! * The `GPT` timer has both 16-bit and 32-bit timer instances.
//!   Unlike the [`timer`](crate::timer) this driver treats all instances
//!   as 16-bit for the sake of brevity.
//! * `RA4M1`: The default configuration sets the CPU and GPT clocks to 48 MHz,
//!   however setting the CPU clock to 32 MHz allows for the GPT clock
//!   to be set to 32 MHz or 64 MHz.
//! * Two module stop gates are shared across all `GPT` instances.  One
//!   for 16-bit and one for 32-bit instances.  Currently they are not
//!   disabled on `Drop` as we're not refcounting `GPT` usage and
//!   `time-driver` uses `GPT32_0`.  Pins are returned to input state on drop.

use core::marker::PhantomData;

use embassy_hal_internal::{Peri, PeripheralType};
use embassy_sync::waitqueue::AtomicWaker;
use paste::paste;

use crate::{
    event_link::InterruptEvent,
    gpio::{Flex, Pin, PortFunction, WithOpenDrain},
    module_stop::ModuleStop,
    pac::{
        self,
        gpt::vals::{Ccr, Gtio, Mode, Odty, Tpcs},
    },
};

/// PWM configuration
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub struct Config {
    /// Timer prescaler. §22.2.12.
    pub divider: Divider,

    /// Where to toggle the output (channel A). §22.3.3.1.
    pub compare_a: u16,

    /// Where to toggle the output (channel B). §22.3.3.1.
    pub compare_b: u16,

    /// Maximum value of `GTCNT`.  The counter will reverse direction at this point.
    pub top: u16,
}

/// PWM clock divider
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Divider {
    /// `PCLKD/1`
    Div1,

    /// `PCLKD/4`
    Div4,

    /// `PCLKD/16`
    Div16,

    /// `PCLKD/64`
    Div64,

    /// `PCLKD/256`
    Div256,

    /// `PCLKD/1024`
    Div1024,
}

/// PWM driver
pub struct Pwm<'d, I: Instance> {
    _instance: PhantomData<&'d I>,
    // These are set to WithOpenDrain because on the RA4M1 all PWM pins have both capabilities
    channel_a: Option<Flex<'d, WithOpenDrain>>,
    channel_b: Option<Flex<'d, WithOpenDrain>>,
}

/// Error type for `Pwm` operations.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug)]
pub enum PwmError {
    /// The duty cycle exceeds the width of the timer or the currently set period.
    InvalidDutyCycle,

    /// Any other kind of error.
    Unknown,
}

/// PWM instance
#[allow(private_bounds)]
pub trait Instance: SealedInstance + ModuleStop + PeripheralType + 'static + Send {}

pub(crate) trait SealedInstance {
    #[cfg(feature = "defmt")]
    const PERIPHERAL: &'static str;
    #[cfg(not(feature = "defmt"))]
    const PERIPHERAL: () = ();

    const CAPTURE_COMP_A_EVENT: InterruptEvent;

    #[allow(dead_code)]
    const CAPTURE_COMP_B_EVENT: InterruptEvent;

    #[allow(dead_code)]
    const COMP_C_EVENT: InterruptEvent;

    fn regs() -> pac::gpt::Gpt;

    fn cmpa_waker() -> &'static AtomicWaker;
}

/// A pin configured to be used as a single PWM channel.
#[allow(private_bounds)]
pub trait PwmChannel: SealedPwmChannel {}

pub(crate) trait SealedPwmChannel {}

/// PWM output pin trait.
#[allow(private_bounds)]
pub trait PwmPin<I: Instance, C: PwmChannel>: SealedPwmPin<I, C> {}

pub(crate) trait SealedPwmPin<I: SealedInstance, C: PwmChannel>:
    Pin + PeripheralType
{
    const PERIPHERAL_FUNC: PortFunction;

    #[inline(always)]
    fn set_pfunc(&self) {
        self.set_as_pf(Self::PERIPHERAL_FUNC);
    }
}

trait SealedPwmChansetter {}
impl<'d, I: Instance> SealedPwmChansetter for Pwm<'d, I> {}

/// Trait that allows setting specific channels with the same function name.
#[allow(private_bounds)]
pub trait PwmChansetter<'d, C: PwmChannel, I: Instance>: SealedPwmChansetter {
    /// Takes ownership of a pin and assigns it to output channel `C`.
    fn with_channel<A: PwmPin<I, C>>(self, pin_a: Peri<'d, A>) -> Self;
}

impl<'d, I: Instance> PwmChansetter<'d, ChanA, I> for Pwm<'d, I> {
    /// This will panic if Channel A has already been set.
    fn with_channel<A: PwmPin<I, ChanA>>(mut self, pin_a: Peri<'d, A>) -> Self {
        assert!(self.channel_b.is_none());

        let pwm = I::regs();

        pwm.gtior().modify(|w| {
            // Start=Low, End=Low, Match=Toggle
            w.set_gtioa(Gtio::_00111);
            w.set_oae(true);
        });
        pwm.gtber().modify(|w| w.set_ccra(Ccr::SingleBuffer));

        pin_a.set_pfunc();
        let pin_a = Flex::new(pin_a);

        self.channel_a = Some(pin_a);
        self
    }
}

impl<'d, I: Instance> PwmChansetter<'d, ChanB, I> for Pwm<'d, I> {
    /// This will panic if Channel B has already been set.
    fn with_channel<B: PwmPin<I, ChanB>>(mut self, pin_b: Peri<'d, B>) -> Self {
        assert!(self.channel_b.is_none());

        let pwm = I::regs();

        pwm.gtior().modify(|w| {
            // Start=Low, End=Low, Match=Toggle
            w.set_gtiob(Gtio::_00111);
            w.set_obe(true);
        });
        pwm.gtber().modify(|w| w.set_ccrb(Ccr::SingleBuffer));

        pin_b.set_pfunc();
        let pin_b = Flex::new(pin_b);

        self.channel_b = Some(pin_b);
        self
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            divider: Divider::Div4,
            compare_a: 0,
            compare_b: 0,
            top: 0xFFFF,
        }
    }
}

impl From<Divider> for u16 {
    fn from(value: Divider) -> Self {
        match value {
            Divider::Div1 => 1,
            Divider::Div4 => 4,
            Divider::Div16 => 16,
            Divider::Div64 => 64,
            Divider::Div256 => 256,
            Divider::Div1024 => 1024,
        }
    }
}

impl From<Tpcs> for Divider {
    fn from(value: Tpcs) -> Self {
        match value {
            Tpcs::Div1 => Self::Div1,
            Tpcs::Div4 => Self::Div4,
            Tpcs::Div16 => Self::Div16,
            Tpcs::Div64 => Self::Div64,
            Tpcs::Div256 => Self::Div256,
            Tpcs::Div1024 => Self::Div1024,
            Tpcs::_RESERVED_6 => unimplemented!(),
            Tpcs::_RESERVED_7 => unimplemented!(),
        }
    }
}

impl From<Divider> for Tpcs {
    fn from(value: Divider) -> Self {
        match value {
            Divider::Div1 => Self::Div1,
            Divider::Div4 => Self::Div4,
            Divider::Div16 => Self::Div16,
            Divider::Div64 => Self::Div64,
            Divider::Div256 => Self::Div256,
            Divider::Div1024 => Self::Div1024,
        }
    }
}

impl<'d, I: Instance> Pwm<'d, I> {
    /// Consumes a `GPT` peripheral instance and returns a driver.
    ///
    /// # Arguments
    /// * `_peri` The `GPT` peripheral e.g. `GPT16_5` or `GPT32_1`.
    /// * `config` configuration
    ///
    /// # Returns
    ///
    /// A `PWM` driver with no output pins assigned and whose counter is initialized to `0` but has not been started.
    pub fn new(peri: Peri<'d, I>, config: Config) -> Self {
        let _ = peri;

        I::start_module();

        let pwm = I::regs();

        pwm.gtcr().modify(|w| w.set_md(Mode::TrianglePwm1));

        pwm.gtcnt().write_value(0);

        let mut this = Self {
            _instance: PhantomData,
            channel_a: None,
            channel_b: None,
        };

        pwm.gtssr().modify(|r| r.set_cstrt(true));

        this.set_config(config);

        this
    }

    /// Takes ownership of a pin and assigns it to output channel A.
    pub fn with_channel_a<A: PwmPin<I, ChanA>>(self, pin_a: Peri<'d, A>) -> Self {
        PwmChansetter::<ChanA, I>::with_channel::<A>(self, pin_a)
    }

    /// Takes ownership of a pin and assigns it to output channel B.
    pub fn with_channel_b<B: PwmPin<I, ChanB>>(self, pin_b: Peri<'d, B>) -> Self {
        PwmChansetter::<ChanB, I>::with_channel::<B>(self, pin_b)
    }

    /// Applies a `Config` struct.
    /// Does not reset the counter.
    pub fn set_config(&mut self, config: Config) {
        let pwm = I::regs();
        pwm.gtcr().modify(|w| w.set_tpcs(config.divider.into()));
        pwm.gtpr().write_value(config.top as u32);

        pwm.gtuddtyc().modify(|w| w.set_oadty(Odty::CompareMatch));
        pwm.gtccra().write_value(config.compare_a as u32);
        pwm.gtccrc().write_value(config.compare_a as u32);

        pwm.gtuddtyc().modify(|w| w.set_obdty(Odty::CompareMatch));
        pwm.gtccrb().write_value(config.compare_b as u32);
        pwm.gtccre().write_value(config.compare_b as u32);
    }

    /// Starts the PWM counter.
    #[inline]
    pub fn start(&mut self) {
        let pwm = I::regs();

        pwm.gtcr().modify(|w| w.set_cst(true));
    }

    /// Stops the PWM counter.
    #[inline]
    pub fn stop(&mut self) {
        let pwm = I::regs();

        pwm.gtcr().modify(|w| w.set_cst(false));
    }

    /// Sets the frequency and duty cycle for both channels.
    ///
    /// # Arguments
    /// * `frequency` Frequency in hertz
    /// * `pct` Duty cycle percentage, range is `0.0..=1.0`
    pub fn set_frequency(&mut self, frequency: u32, pct: f32) -> Result<(), PwmError> {
        let pwm = I::regs();
        let clocks = crate::clock::clock_status();
        let divider: Divider = pwm.gtcr().read().tpcs().into();
        let divider: u16 = divider.into();
        let divider = divider as f32;
        let pwm_clk = clocks.peripheral_d.to_Hz() as f32;
        let period = (pwm_clk / divider) / (frequency as f32 * 2.0);

        trace!(
            "{}set_freq(freq={}, pct={}%, divider={}, clk={}, period={})",
            I::PERIPHERAL,
            frequency,
            pct * 100.0,
            divider,
            pwm_clk,
            period,
        );

        if period < 2.0 || period > f32::from(u16::MAX - 2) {
            error!(
                "{}Unable to set frequency={} Hz, max allowable={}",
                I::PERIPHERAL,
                frequency,
                (pwm_clk / (divider * 4.0)) as u32,
            );
            return Err(PwmError::InvalidDutyCycle);
        }

        pwm.gtpr().write_value(period as u32);
        self.set_duty_pct(pct);

        Ok(())
    }

    /// Sets the duty cycle for both channels to the same value.
    ///
    /// # Arguments
    /// `pct` Duty cycle percentage, range is `0.0..=1.0`
    #[inline]
    pub fn set_duty_pct(&mut self, pct: f32) {
        self.set_duty_pct_a(pct);
        self.set_duty_pct_b(pct);
    }

    /// Sets the duty cycle for channel A if it's been assigned to a pin.
    ///
    /// # Arguments
    /// `pct` Duty cycle percentage, range is `0.0..=1.0`
    pub fn set_duty_pct_a(&mut self, pct: f32) {
        if self.channel_a.is_none() {
            return;
        }

        let pwm = I::regs();
        let pct = pct.clamp(0.0, 1.0);
        let period = pwm.gtpr().read() as f32;
        let cmp = (period * (1.0 - pct)) as u32;

        if cmp == 0 {
            pwm.gtuddtyc().modify(|w| w.set_oadty(Odty::On));
        } else if cmp >= period as u32 {
            pwm.gtuddtyc().modify(|w| w.set_oadty(Odty::Off));
        } else {
            // This will center the peak

            pwm.gtuddtyc().modify(|w| w.set_oadty(Odty::CompareMatch));
            pwm.gtccra().write_value(cmp);
            pwm.gtccrc().write_value(cmp);
        }
    }

    /// Sets the duty cycle for channel A if it's been assigned to a pin.
    ///
    /// # Arguments
    /// `duty` Raw value, range is `0.0..=period`
    pub fn set_duty_a(&mut self, duty: u32) -> Result<(), PwmError> {
        if self.channel_a.is_none() {
            return Ok(());
        }

        let pwm = I::regs();
        let period = pwm.gtpr().read();

        #[cfg(feature = "strict-assert")]
        assert!(period <= u32::from(u16::MAX));
        if period > u32::from(u16::MAX) {
            Err(PwmError::InvalidDutyCycle)?;
        }

        if duty == 0 {
            pwm.gtuddtyc().modify(|w| w.set_oadty(Odty::On));
        } else if duty >= period {
            pwm.gtuddtyc().modify(|w| w.set_oadty(Odty::Off));
        } else {
            // This will center the peak

            pwm.gtuddtyc().modify(|w| w.set_oadty(Odty::CompareMatch));
            pwm.gtccra().write_value(duty);
            pwm.gtccrc().write_value(duty);
        }

        Ok(())
    }

    /// Sets the duty cycle for channel B if it's been assigned to a pin.
    ///
    /// # Arguments
    /// `pct` Duty cycle, range is 0.0..=1.0
    pub fn set_duty_pct_b(&mut self, pct: f32) {
        if self.channel_b.is_none() {
            return;
        }

        let pwm = I::regs();
        let pct = pct.clamp(0.0, 1.0);
        let period = pwm.gtpr().read() as f32;
        let cmp = (period * (1.0 - pct)) as u32;

        if cmp == 0 {
            pwm.gtuddtyc().modify(|w| w.set_obdty(Odty::On));
        } else if cmp >= period as u32 {
            pwm.gtuddtyc().modify(|w| w.set_obdty(Odty::Off));
        } else {
            // This will center the peak

            pwm.gtuddtyc().modify(|w| w.set_obdty(Odty::CompareMatch));
            pwm.gtccrb().write_value(cmp);
            pwm.gtccre().write_value(cmp);
        }
    }

    /// Sets the duty cycle for channel B if it's been assigned to a pin.
    ///
    /// # Arguments
    /// `duty` Raw value, range is `0.0..=period`
    pub fn set_duty_b(&mut self, duty: u32) -> Result<(), PwmError> {
        if self.channel_b.is_none() {
            return Ok(());
        }

        let pwm = I::regs();
        let period = pwm.gtpr().read();

        #[cfg(feature = "strict-assert")]
        assert!(period <= u32::from(u16::MAX));
        if period > u32::from(u16::MAX) {
            Err(PwmError::InvalidDutyCycle)?;
        }

        if duty == 0 {
            pwm.gtuddtyc().modify(|w| w.set_obdty(Odty::On));
        } else if duty >= period {
            pwm.gtuddtyc().modify(|w| w.set_obdty(Odty::Off));
        } else {
            // This will center the peak

            pwm.gtuddtyc().modify(|w| w.set_obdty(Odty::CompareMatch));
            pwm.gtccrb().write_value(duty);
            pwm.gtccre().write_value(duty);
        }

        Ok(())
    }
}

impl<'d, I: Instance> Drop for Pwm<'d, I> {
    fn drop(&mut self) {
        self.stop();
        I::stop_module();
    }
}

macro_rules! declare_pwm_channel {
    ($chan:ident) => {
        paste! {
            // TODO: macro expansion in rustdoc?
            #[allow(missing_docs)]
            pub enum [< Chan $chan >]  {}
            impl PwmChannel for [< Chan $chan >] {}
            impl SealedPwmChannel for [< Chan $chan >] {}
        }
    };
}

/// Declares a PWM pin
///
/// # Arguments
/// * `$instance` GPT instance e.g. `GPT32_0`, `GPT16_2`
/// * `$chan` channel either `ChanA` or `ChanB`
/// * `$pin` peripheral name for the pin
/// * `$pf` Peripheral Function
macro_rules! pwm_pin {
    ($instance:ident, $chan:ident, $pin:ident, $pf:ident) => {
        impl crate::pwm::PwmPin<crate::peripherals::$instance, crate::pwm::$chan>
            for crate::peripherals::$pin
        {
        }

        impl crate::pwm::SealedPwmPin<crate::peripherals::$instance, crate::pwm::$chan>
            for crate::peripherals::$pin
        {
            const PERIPHERAL_FUNC: crate::gpio::PortFunction = crate::gpio::PortFunction::$pf;
        }
    };
}
pub(crate) use pwm_pin;

declare_pwm_channel!(A);
declare_pwm_channel!(B);

macro_rules! gpt_instance {
    ($peripheral:ident, $ccmpa:ident, $ccmpb:ident, $cmpc:ident, $overflow:ident, $underflow:ident) => {
        impl crate::pwm::Instance for crate::peripherals::$peripheral {}
        impl crate::pwm::SealedInstance for crate::peripherals::$peripheral {
            #[cfg(feature = "defmt")]
            const PERIPHERAL: &'static str = concat!(stringify!($peripheral), ": ");

            const CAPTURE_COMP_A_EVENT: crate::event_link::InterruptEvent =
                crate::event_link::InterruptEvent::$ccmpa;
            const CAPTURE_COMP_B_EVENT: crate::event_link::InterruptEvent =
                crate::event_link::InterruptEvent::$ccmpb;
            const COMP_C_EVENT: crate::event_link::InterruptEvent =
                crate::event_link::InterruptEvent::$cmpc;

            #[inline(always)]
            fn regs() -> crate::pac::gpt::Gpt {
                crate::pac::$peripheral
            }

            fn cmpa_waker() -> &'static embassy_sync::waitqueue::AtomicWaker {
                static WAKER: embassy_sync::waitqueue::AtomicWaker =
                    embassy_sync::waitqueue::AtomicWaker::new();
                &WAKER
            }
        }
    };
}
pub(crate) use gpt_instance;

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

impl<'d, I: Instance> embedded_hal_1::pwm::ErrorType for Pwm<'d, I> {
    type Error = PwmError;
}

impl<'d, I: Instance> embedded_hal_1::pwm::SetDutyCycle for Pwm<'d, I> {
    fn max_duty_cycle(&self) -> u16 {
        let pwm = I::regs();
        let period = pwm.gtpr().read();
        assert!(period <= u32::from(u16::MAX));
        period as u16
    }

    fn set_duty_cycle(&mut self, duty: u16) -> Result<(), Self::Error> {
        if self.channel_a.is_some() {
            self.set_duty_a(duty as u32)?;
        }

        if self.channel_b.is_some() {
            self.set_duty_b(duty as u32)?;
        }

        Ok(())
    }
}