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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! Universal Asynchronous Receiver-Transmitter (`SCI_B`).

use core::{future::poll_fn, marker::PhantomData, task::Poll};

use cortex_m::asm;
use embassy_hal_internal::{
    Peri, PeripheralType, atomic_ring_buffer::RingBuffer, interrupt::InterruptExt as _,
};
use embassy_sync::waitqueue::AtomicWaker;

use crate::{
    event_link::{IcuInterrupt as _, InterruptEvent},
    gpio::{Pin, PortFunction},
    interrupt::{
        self,
        typelevel::{Handler as InterruptHandler, Interrupt as InterruptType},
    },
    module_stop::ModuleStop,
    pac::{
        self,
        sci::vals::{Chr, Cke, Cks, Mode, Pm, Stop},
    },
    uart::{
        Async, BaudGenConfig, Blocking, DataBits, Parity, StopBits, TransferMode, calc_baud_gen,
    },
};

/// UART configuration
#[non_exhaustive]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Config {
    /// Baud rate
    pub baud_rate: u32,

    /// Number of data bits.
    /// Note: 9 bit data is not yet supported.
    #[allow(missing_docs)]
    pub data_bits: DataBits,

    /// Parity type
    #[allow(missing_docs)]
    pub parity: Parity,

    /// Number of stop bits.
    #[allow(missing_docs)]
    pub stop_bits: StopBits,
}

/// Interrupt handler that handles incoming data for an `SCI` instance.
pub struct RxInterruptHandler<I: Instance> {
    _phantom: PhantomData<I>,
}

/// Interrupt handler that handles outgoing data (transmission end) for an `SCI` instance.
pub struct TeInterruptHandler<I: Instance> {
    _phantom: PhantomData<I>,
}

/// Interrupt handler that handles outgoing data (tx buffer empty) for an `SCI` instance.
pub struct TxInterruptHandler<I: Instance> {
    _phantom: PhantomData<I>,
}

#[allow(private_bounds)]
pub struct Uart<'d, I: Instance, M: TransferMode> {
    _phantom: PhantomData<&'d I>,
    io_mode: M,
}

/// UART error
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum UartError {
    /// Framing error
    Framing,
    /// RX buffer overrun
    Overrun,
    /// Parity check error
    Parity,
}

#[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 RX_INTERRUPT_EVENT: InterruptEvent;
    const TE_INTERRUPT_EVENT: InterruptEvent;
    const TX_INTERRUPT_EVENT: InterruptEvent;

    const FIFO_DEPTH: u8 = 16;

    fn regs() -> pac::sci::Sci;

    /// # Returns
    ///
    /// Static reference to the statically allocated [`RingBuffer`] for receive operations.
    fn rx_buffer() -> &'static RingBuffer;

    /// # Returns
    ///
    /// Static reference to the statically allocated [`RingBuffer`] for transmit operations.
    fn tx_buffer() -> &'static RingBuffer;

    /// Waker for receive events.
    fn rx_waker() -> &'static AtomicWaker;

    /// Waker for "transmit end" events.
    fn te_waker() -> &'static AtomicWaker;

    /// Waker for transmit buffer empty events.
    fn tx_waker() -> &'static AtomicWaker;
}

/// A pin that can be used for reception.
#[allow(private_bounds)]
pub trait RxPin<I: Instance>: SealedRxPin<I> {}

/// A pin that can be used for transmission.
#[allow(private_bounds)]
pub trait TxPin<I: Instance>: SealedTxPin<I> {}

pub(crate) trait SealedRxPin<I: SealedInstance>: Pin + PeripheralType {
    const PERIPHERAL_FUNC: PortFunction;

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

pub(crate) trait SealedTxPin<I: SealedInstance>: Pin + PeripheralType {
    const PERIPHERAL_FUNC: PortFunction;

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

impl Default for Config {
    fn default() -> Self {
        Self {
            baud_rate: 9600,
            data_bits: DataBits::DataBits8,
            parity: Parity::None,
            stop_bits: StopBits::Stop1,
        }
    }
}

impl<'d, I: Instance> Uart<'d, I, Async> {
    /// Creates a new Uart instance that implements interrupt driven, asynchronous I/O APIs.
    #[allow(private_bounds)]
    pub fn new_async<RxInt: InterruptType, TeInt: InterruptType, TxInt: InterruptType>(
        _peri: Peri<'d, I>,
        tx_pin: Peri<'d, impl TxPin<I>>,
        tx_buffer: &'d mut [u8],
        rx_pin: Peri<'d, impl RxPin<I>>,
        rx_buffer: &'d mut [u8],
        irqs: impl interrupt::typelevel::Binding<RxInt, RxInterruptHandler<I>>
        + interrupt::typelevel::Binding<TeInt, TeInterruptHandler<I>>
        + interrupt::typelevel::Binding<TxInt, TxInterruptHandler<I>>
        + 'd,
        config: Config,
    ) -> Self {
        info!("{}{}", I::PERIPHERAL, config);

        let clock_config = crate::clock::clock_status();
        let mut this = Self::new_inner(tx_pin, tx_buffer, rx_pin, rx_buffer, irqs);

        this.set_data_bits_inner(config.data_bits);
        this.set_parity_inner(config.parity);
        this.set_stop_bits_inner(config.stop_bits);

        let brr_config = calc_baud_gen(config.baud_rate, clock_config.sci.unwrap()).unwrap();

        info!("{}{}", I::PERIPHERAL, brr_config);
        Self::set_baud_from_config(&brr_config);

        let sci = I::regs();

        // We can leave the receiver on, but not the transmitter as enabling the transmitter in
        // combination with the TX interrupt is what kicks off the whole transmit procedure.
        sci.ccr0().modify(|r| {
            r.set_re(true);
            r.set_rie(true);
        });

        this
    }

    fn new_inner<RxInt: InterruptType, TxInt: InterruptType, TeInt: InterruptType>(
        tx_pin: Peri<'d, impl TxPin<I>>,
        tx_buffer: &'d mut [u8],
        rx_pin: Peri<'d, impl RxPin<I>>,
        rx_buffer: &'d mut [u8],
        irqs: impl interrupt::typelevel::Binding<RxInt, RxInterruptHandler<I>>
        + interrupt::typelevel::Binding<TxInt, TxInterruptHandler<I>>
        + interrupt::typelevel::Binding<TeInt, TeInterruptHandler<I>>
        + 'd,
    ) -> Self {
        let _ = irqs;

        I::start_module();

        let sci = I::regs();

        sci.ccr0().modify(|r| {
            r.set_re(false);
            r.set_rie(false);
            r.set_te(false);
            r.set_teie(false);
            r.set_tie(false);
        });
        while sci.cesr().read().tist() {}

        // Enable FIFO
        sci.ccr3().modify(|r| r.set_fm(true));
        let ttrg = I::FIFO_DEPTH / 2;
        debug!("{}TTRG: {}", I::PERIPHERAL, ttrg);
        sci.fcr().modify(|r| r.set_ttrg(ttrg));

        // not-smart card mode
        sci.ccr3().modify(|r| {
            r.set_mod_(Mode::AyncMp);
            r.set_rxdesel(false);
            r.set_cke(Cke::_00);
        });

        sci.ccr2().modify(|r| {
            r.set_abcs(false);
            r.set_abcse(false);
            r.set_bgdm(false);
            r.set_brme(false);
        });

        sci.ccr1().write(|r| {
            r.set_spb2dt(false);
            r.set_spb2io(false);
        });

        // Move pins over to SCI
        trace!("P{}RX=p{}/{}", I::PERIPHERAL, rx_pin._port(), rx_pin._pin());
        rx_pin.set_pfunc();

        trace!("{}TX=p{}/{}", I::PERIPHERAL, tx_pin._port(), tx_pin._pin());
        tx_pin.set_pfunc();

        let rx_len = rx_buffer.len();
        unsafe { I::rx_buffer().init(rx_buffer.as_mut_ptr(), rx_len) };

        let tx_len = tx_buffer.len();
        unsafe { I::tx_buffer().init(tx_buffer.as_mut_ptr(), tx_len) };

        // Safety: Interrupt handlers are defined by the irqs argument and thus the interrupts are safe to enable.
        unsafe {
            // Enable interrupts in NVIC. We can largely ignore the NVIC after this as all of the
            // peripheral interrupts are going to be managed by the ICU and/or ELC.
            RxInt::IRQ.enable();
            TeInt::IRQ.enable();
            TxInt::IRQ.enable();

            // Enable in ICU
            RxInt::IRQ.icu_enable(I::RX_INTERRUPT_EVENT);
            TeInt::IRQ.icu_enable(I::TE_INTERRUPT_EVENT);
            TxInt::IRQ.icu_enable(I::TX_INTERRUPT_EVENT);
        }

        Self {
            _phantom: PhantomData,
            io_mode: Async {
                rx_int: RxInt::IRQ,
                tx_int: TxInt::IRQ,
            },
        }
    }

    /// Reads data from the UART.
    ///
    /// # Returns
    ///
    /// Returns when there is data in the RX [`RingBuffer`].
    /// `buf` is not guaranteed to be full and the length of its contents is returned.
    pub async fn read(&self, buf: &mut [u8]) -> Result<usize, UartError> {
        poll_fn(|cx| {
            let mut buf_pos = 0;
            let mut reader = unsafe { I::rx_buffer().reader() };
            let mut data = reader.pop_slice();

            while !data.is_empty() && buf_pos < buf.len() {
                let data_len = data.len().min(buf.len() - buf_pos);
                buf[buf_pos..buf_pos + data_len].copy_from_slice(&data[..data_len]);
                buf_pos += data_len;

                let pending = I::rx_buffer().is_full();
                reader.pop_done(data_len);

                if pending {
                    self.io_mode.rx_int.icu_pend();
                }

                data = reader.pop_slice();
            }

            if buf_pos != 0 {
                Poll::Ready(Ok(buf_pos))
            } else {
                I::rx_waker().register(cx.waker());
                Poll::Pending
            }
        })
        .await
    }

    pub async fn write(&mut self, data: &[u8]) -> Result<usize, UartError> {
        let sci = I::regs();

        let mut written: usize = 0;
        let mut writer = unsafe { I::tx_buffer().writer() };

        sci.fcr().modify(|r| r.set_tfrst(true));

        poll_fn(|cx| {
            if written < data.len() {
                I::tx_waker().register(cx.waker());

                if I::tx_buffer().is_full() {
                    trace!("{}TX buffer full in async write", I::PERIPHERAL);
                    return Poll::Pending;
                }

                let out = writer.push_slice();
                let chunk_len = out.len().min(data.len().saturating_sub(written));
                out[..chunk_len].copy_from_slice(&data[written..(written + chunk_len)]);
                written += chunk_len;

                writer.push_done(chunk_len);

                if !sci.cesr().read().tist() {
                    sci.ccr0().modify(|r| {
                        r.set_te(true);
                        r.set_tie(true);
                    });
                    while !sci.cesr().read().tist() {}
                }

                if written < data.len() {
                    return Poll::Pending;
                }
            }
            I::te_waker().register(cx.waker());

            // If we're still waiting for the FIFO to write everything to the wire
            if !sci.csr().read().tend() {
                return Poll::Pending;
            }

            Poll::Ready(Ok(written))
        })
        .await
    }
}

impl<'d, I: Instance> Uart<'d, I, Blocking> {
    /// Creates a new Uart instance that implements blocking I/O APIs.
    #[allow(private_bounds)]
    pub fn new_blocking(
        _peri: Peri<'d, I>,
        tx_pin: Peri<'d, impl TxPin<I>>,
        rx_pin: Peri<'d, impl RxPin<I>>,
        config: Config,
    ) -> Self {
        info!("{}{}", I::PERIPHERAL, config);

        let clock_config = crate::clock::clock_status();
        let mut this = Self::new_inner(tx_pin, rx_pin);

        this.set_data_bits_inner(config.data_bits);
        this.set_parity_inner(config.parity);
        this.set_stop_bits_inner(config.stop_bits);

        let brr_config = calc_baud_gen(config.baud_rate, clock_config.sci.unwrap()).unwrap();

        info!("{}{}", I::PERIPHERAL, brr_config);
        Self::set_baud_from_config(&brr_config);

        let sci = I::regs();

        // We can leave the receiver on, but not the transmitter as enabling the transmitter in
        // combination with the TX interrupt is what kicks off the whole transmit procedure.
        sci.ccr0().modify(|r| {
            r.set_re(true);
            r.set_rie(true);
        });

        this
    }
    fn new_inner(tx_pin: Peri<'d, impl TxPin<I>>, rx_pin: Peri<'d, impl RxPin<I>>) -> Self {
        I::start_module();

        let sci = I::regs();

        sci.ccr0().modify(|r| {
            r.set_re(false);
            r.set_rie(false);
            r.set_te(false);
            r.set_teie(false);
            r.set_tie(false);
        });
        while sci.cesr().read().tist() {}

        // Enable FIFO
        sci.ccr3().modify(|r| r.set_fm(true));
        // TODO: Is this the value we want?
        sci.fcr().modify(|r| r.set_ttrg(I::FIFO_DEPTH));

        // not-smart card mode
        sci.ccr3().modify(|r| {
            r.set_mod_(Mode::AyncMp);
            r.set_rxdesel(false);
            r.set_cke(Cke::_00);
        });

        sci.ccr2().modify(|r| {
            r.set_abcs(false);
            r.set_abcse(false);
            r.set_bgdm(false);
            r.set_brme(false);
        });

        sci.ccr1().write(|r| {
            r.set_spb2dt(false);
            r.set_spb2io(false);
        });

        // Move pins over to SCI
        trace!("P{}RX=p{}/{}", I::PERIPHERAL, rx_pin._port(), rx_pin._pin());
        rx_pin.set_pfunc();

        trace!("{}TX=p{}/{}", I::PERIPHERAL, tx_pin._port(), tx_pin._pin());
        tx_pin.set_pfunc();

        Self {
            _phantom: PhantomData,
            io_mode: Blocking {},
        }
    }

    /// Reads data from the UART, blocks until `data` is full.
    #[inline(always)]
    pub fn blocking_read(&self, data: &mut [u8]) {
        let sci = I::regs();

        for byte in data.iter_mut() {
            let mut fifo;
            loop {
                fifo = sci.frsr().read();
                if fifo.r() != 0 {
                    break;
                }
            }

            *byte = (sci.rdr().read().rdat() & 0xFF) as u8;
        }
    }

    /// Writes `data` to the UART, blocking until the last byte has been sent out on the wire.
    pub fn blocking_write(&mut self, data: &[u8]) {
        let sci = I::regs();

        let mut written: usize = 0;

        sci.ccr0().modify(|r| r.set_te(true));
        while !sci.cesr().read().tist() {}

        while written != data.len() {
            let fifo_contents = sci.ftsr().read().t();
            let fifo_available = usize::from(I::FIFO_DEPTH - fifo_contents);
            let write_len = (data.len() - written).min(fifo_available);

            for byte in data.iter().skip(written).take(write_len) {
                sci.tdr_by_ll().write_value(*byte);
            }
            written += write_len;
        }

        while !sci.csr().read().tend() {
            asm::nop();
        }

        sci.ccr0().modify(|r| r.set_te(false));
        while sci.cesr().read().tist() {}
    }
}

impl<I: Instance, RxInt: InterruptType> InterruptHandler<RxInt> for RxInterruptHandler<I> {
    unsafe fn on_interrupt() {
        trace!("RxI");

        let sci = I::regs();
        let mut writer = unsafe { I::rx_buffer().writer() };
        let buf = writer.push_slice();

        match buf.is_empty() {
            false => {
                let fifo_len = sci.frsr().read().r() as _;
                let read_len = buf.len().min(fifo_len);

                for out_byte in buf.iter_mut().take(read_len) {
                    *out_byte = (sci.rdr().read().rdat() & 0xFF) as u8;
                }
                writer.push_done(read_len);
                sci.cfclr().write(|r| r.set_rdrfc(true));

                I::rx_waker().wake();

                if read_len != fifo_len {
                    trace!("{}RX Buffer full, FIFO drain={}", I::PERIPHERAL, read_len);
                } else {
                    RxInt::IRQ.icu_unpend();
                }
            }
            true => {
                let fifo_free = I::FIFO_DEPTH - sci.frsr().read().r();

                warn!("{}RX Buffer full, FIFO cap={}", I::PERIPHERAL, fifo_free);

                RxInt::IRQ.icu_unpend();

                I::rx_waker().wake();

                if sci.csr().read().orer() {
                    error!("{}Overrun, dropping 1", I::PERIPHERAL);
                    sci.cfclr().write(|r| r.set_orerc(false));
                    RxInt::IRQ.icu_unpend();
                }
            }
        }
    }
}

impl<I: Instance, TeInt: InterruptType> InterruptHandler<TeInt> for TeInterruptHandler<I> {
    unsafe fn on_interrupt() {
        trace!("TeI");
        TeInt::IRQ.icu_unpend();

        let sci = I::regs();

        if I::tx_buffer().is_empty() {
            while !sci.csr().read().tend() {}

            sci.ccr0().modify(|r| {
                r.set_te(false);
                r.set_teie(false);
                r.set_tie(false);
            });
            while sci.cesr().read().tist() {}

            I::te_waker().wake();
        } else {
            sci.cfclr().write(|r| r.set_tdrec(true));

            sci.ccr0().modify(|r| {
                r.set_te(true);
                r.set_tie(true);
            });
            while !sci.cesr().read().tist() {}

            I::tx_waker().wake();
        }
    }
}

impl<I: Instance, TxInt: InterruptType> InterruptHandler<TxInt> for TxInterruptHandler<I> {
    unsafe fn on_interrupt() {
        trace!("TxI");
        TxInt::IRQ.icu_unpend();
        TxInt::IRQ.unpend();

        let sci = I::regs();
        let mut tx_reader = unsafe { I::tx_buffer().reader() };

        let out_buf = tx_reader.pop_slice();

        if out_buf.is_empty() {
            sci.ccr0().modify(|r| {
                r.set_teie(true);
                r.set_tie(false);
            });

            return;
        }

        let out_len = out_buf.len();
        let fifo_available = usize::from(I::FIFO_DEPTH - sci.ftsr().read().t());

        if fifo_available == 0 {
            sci.ccr0().modify(|r| {
                r.set_teie(false);
                r.set_tie(true);
            });
            return;
        }

        if out_len > fifo_available {
            for byte in out_buf[0..fifo_available].iter() {
                sci.tdr_by_ll().write_value(*byte);
            }

            tx_reader.pop_done(fifo_available);
        } else {
            for byte in out_buf[0..out_len].iter() {
                sci.tdr_by_ll().write_value(*byte);
            }
            tx_reader.pop_done(out_len);
        }

        I::tx_waker().wake();
        sci.cfclr().write(|r| r.set_tdrec(true));
    }
}

impl<'d, I: Instance, M: TransferMode> Uart<'d, I, M> {
    /// Sets the number of bits in a byte.
    ///
    /// Note:
    /// * 9 bit data is supported by the underlying hardware but not yet by this driver.
    /// * This will disable the transmitter and temporarily disable the receiver (RA4M1 §28.2.9 note 4).
    #[inline]
    pub fn set_data_bits(&mut self, n: DataBits) {
        let sci = I::regs();

        sci.ccr0().modify(|r| {
            r.set_re(false);
            r.set_te(false);
        });
        while sci.cesr().read().tist() {}

        self.set_data_bits_inner(n);

        sci.ccr0().modify(|r| r.set_re(true));
    }

    fn set_data_bits_inner(&mut self, n: DataBits) {
        let sci = I::regs();

        let data_bits = match n {
            DataBits::DataBits7 => Chr::_7bit,
            DataBits::DataBits8 => Chr::_8bit,
            DataBits::DataBits9 => Chr::_9bit,
        };

        sci.ccr3().modify(|r| r.set_chr(data_bits));
    }

    /// Sets baud rate for the `SCI` instance.
    ///
    /// Note: This will disable the transmitter and temporarily disable the receiver (§28.2.9 note 4).
    pub fn set_parity(&mut self, parity: Parity) {
        let sci = I::regs();

        sci.ccr0().modify(|r| {
            r.set_re(false);
            r.set_te(false);
        });
        while sci.cesr().read().tist() {}

        self.set_parity_inner(parity);

        sci.ccr0().modify(|r| r.set_re(true));
    }

    fn set_parity_inner(&mut self, parity: Parity) {
        let sci = I::regs();

        let (pe, pm) = match parity {
            Parity::Even => (true, Pm::Even),
            Parity::Odd => (true, Pm::Odd),
            Parity::None => (false, Pm::Even),
        };

        sci.ccr1().modify(|r| {
            r.set_pe(pe);
            r.set_pm(pm);
        });
    }

    /// Set stop bit length.
    ///
    /// Note: This will disable the transmitter and temporarily disable the receiver (§28.2.9 note 4).
    pub fn set_stop_bits(&mut self, stop_bits: StopBits) {
        let sci = I::regs();

        sci.ccr0().modify(|r| {
            r.set_re(false);
            r.set_te(false);
        });
        while sci.cesr().read().tist() {}

        self.set_stop_bits_inner(stop_bits);

        sci.ccr0().modify(|r| r.set_re(true));
    }

    fn set_stop_bits_inner(&mut self, stop_bits: StopBits) {
        let sci = I::regs();

        // Set it up for No Parity, 1 stop bit
        sci.ccr3().modify(|r| {
            match stop_bits {
                StopBits::Stop1 => r.set_stop(Stop::Stop1),
                StopBits::Stop2 => r.set_stop(Stop::Stop2),
            };
        });
    }

    fn set_baud_from_config(brr_config: &BaudGenConfig) {
        let sci = I::regs();

        sci.ccr2().modify(|r| {
            r.set_brr(u8::try_from(brr_config.big_n).expect("SCI big_n > 255"));
            r.set_mddr(0);
            r.set_brme(false);
            r.set_cks(Cks::from_bits(
                u8::try_from(brr_config.small_n).expect("SCI small_n > 255"),
            ))
        });

        sci.ccr0().modify(|r| r.set_re(true));
    }
}

impl<'d, I: Instance, M: TransferMode> Drop for Uart<'d, I, M> {
    fn drop(&mut self) {
        I::stop_module();
    }
}

macro_rules! tx_pin {
    ($sci:ident, $pin:ident, $pfunc:ident) => {
        impl crate::uart::sci::TxPin<crate::peripherals::$sci> for crate::peripherals::$pin {}
        impl crate::uart::sci::SealedTxPin<crate::peripherals::$sci> for crate::peripherals::$pin {
            const PERIPHERAL_FUNC: crate::gpio::PortFunction = crate::gpio::PortFunction::$pfunc;
        }
    };
}
pub(crate) use tx_pin;

macro_rules! rx_pin {
    ($sci:ident, $pin:ident, $pfunc:ident) => {
        impl crate::uart::sci::RxPin<crate::peripherals::$sci> for crate::peripherals::$pin {}
        impl crate::uart::sci::SealedRxPin<crate::peripherals::$sci> for crate::peripherals::$pin {
            const PERIPHERAL_FUNC: crate::gpio::PortFunction = crate::gpio::PortFunction::$pfunc;
        }
    };
}
pub(crate) use rx_pin;

macro_rules! instance_impl {
    ($instance:ident, $rx_int:ident, $te_int:ident, $tx_int:ident) => {
        impl crate::uart::sci::Instance for peripherals::$instance {}

        impl crate::uart::sci::SealedInstance for crate::peripherals::$instance {
            #[cfg(feature = "defmt")]
            const PERIPHERAL: &'static str = concat!(stringify!($instance), ": ");

            const RX_INTERRUPT_EVENT: crate::event_link::InterruptEvent =
                crate::event_link::InterruptEvent::$rx_int;
            const TE_INTERRUPT_EVENT: crate::event_link::InterruptEvent =
                crate::event_link::InterruptEvent::$te_int;
            const TX_INTERRUPT_EVENT: crate::event_link::InterruptEvent =
                crate::event_link::InterruptEvent::$tx_int;

            #[inline]
            fn regs() -> crate::pac::sci::Sci {
                crate::pac::$instance
            }

            fn rx_buffer() -> &'static embassy_hal_internal::atomic_ring_buffer::RingBuffer {
                static RX_BUF: embassy_hal_internal::atomic_ring_buffer::RingBuffer =
                    embassy_hal_internal::atomic_ring_buffer::RingBuffer::new();
                &RX_BUF
            }

            fn tx_buffer() -> &'static embassy_hal_internal::atomic_ring_buffer::RingBuffer {
                static TX_BUF: embassy_hal_internal::atomic_ring_buffer::RingBuffer =
                    embassy_hal_internal::atomic_ring_buffer::RingBuffer::new();
                &TX_BUF
            }

            fn rx_waker() -> &'static embassy_sync::waitqueue::AtomicWaker {
                static RX_WAKER: embassy_sync::waitqueue::AtomicWaker =
                    embassy_sync::waitqueue::AtomicWaker::new();
                &RX_WAKER
            }

            fn te_waker() -> &'static embassy_sync::waitqueue::AtomicWaker {
                static TE_WAKER: embassy_sync::waitqueue::AtomicWaker =
                    embassy_sync::waitqueue::AtomicWaker::new();
                &TE_WAKER
            }

            fn tx_waker() -> &'static embassy_sync::waitqueue::AtomicWaker {
                static TX_WAKER: embassy_sync::waitqueue::AtomicWaker =
                    embassy_sync::waitqueue::AtomicWaker::new();
                &TX_WAKER
            }
        }
    };
}
pub(crate) use instance_impl;