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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
//! I2C Bus Interface (`IIC`).
//!
//! # Notes
//! Is it really worth allocating a buffer and grabbing an interrupt to make up for the lack of built-in FIFO?
//! # TODO
//! * Error checking and handling
//! * Clock config for arbitrary rates

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 embedded_hal_1::i2c::SevenBitAddress;

use crate::{
    dtc::{Channel as DtcChannel, DtcInterruptHandler, Instance as DtcInstance},
    event_link::{IcuInterrupt as _, InterruptEvent},
    gpio::{Flex, Pin, PortFunction, WithOpenDrain},
    interrupt::{
        self,
        typelevel::{Handler as InterruptHandler, Interrupt as InterruptType},
    },
    module_stop::ModuleStop,
    pac::{self, iic::vals::Cks},
    write_protect::ProtectedModify,
};

/// Represents one of the possible modes of transfer e.g. spin-wait), interrupt, or DMA.
#[allow(private_bounds)]
pub trait TransferMode: SealedTransferMode {}
trait SealedTransferMode {}

/// Synchronous mode.
pub struct Blocking;

/// Interrupt driven asynchronous mode.
pub struct Async<RxInt: InterruptType, TeInt: InterruptType, TxInt: InterruptType> {
    _rx: PhantomData<RxInt>,
    _te: PhantomData<TeInt>,
    _tx: PhantomData<TxInt>,
}

/// DTC driven asynchronous mode.
pub struct Dtc<RxInt: InterruptType, TxDtc: DtcInstance> {
    rx_dtc: PhantomData<RxInt>,
    tx_dtc: DtcChannel<TxDtc>,
}

impl TransferMode for Blocking {}
impl SealedTransferMode for Blocking {}

impl<RxInt: InterruptType, TeInt: InterruptType, TxInt: InterruptType> TransferMode
    for Async<RxInt, TeInt, TxInt>
{
}

impl<RxInt: InterruptType, TeInt: InterruptType, TxInt: InterruptType> SealedTransferMode
    for Async<RxInt, TeInt, TxInt>
{
}

impl<RxInt: InterruptType, TxDtc: DtcInstance> TransferMode for Dtc<RxInt, TxDtc> {}
impl<RxInt: InterruptType, TxDtc: DtcInstance> SealedTransferMode for Dtc<RxInt, TxDtc> {}

/// I2C driver for the `IIC` peripheral.
///
/// # Notes
///
/// While there are internal pull-up resistors on the pins attached to the `IIC` peripherals they do *not* function in peripheral mode.
#[allow(private_bounds)]
pub struct I2c<'d, I: Instance, M: TransferMode> {
    _instance: PhantomData<&'d I>,
    mode: M,
    // These are set to WithOpenDrain because on the RA4M1 all I2C pins have both capabilities
    _scl: Flex<'d, WithOpenDrain>,
    _sda: Flex<'d, WithOpenDrain>,
}

/// Clock configuration for an [`I2c`] instance.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ClockConfig {
    /// Divider for the `IIC` reference clock (`IICϕ`). `PCKLB / divider = IICϕ`. §29.2.3.
    pub divider: Divider,

    /// `I2C` Low-level period (`t_low`). Units are `IICϕ` cycles? §29.2.15.
    pub low: u8,

    /// `I2C` High-level period (`t_high`). Units are `IICϕ` cycles? §29.2.16.
    pub high: u8,
}

/// `IICÏ•` divider
#[derive(Copy, Clone, Debug)]
#[allow(missing_docs)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Divider {
    Div1 = 0x0,
    Div2 = 0x01,
    Div4 = 0x02,
    Div8 = 0x03,
    Div16 = 0x04,
    Div32 = 0x05,
    Div64 = 0x06,
    Div128 = 0x07,
}

/// Max supported speed is 400 kHz § 29.1
#[derive(Debug, Copy, Clone, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum I2cSpeed {
    /// 100 kHz
    #[default]
    Normal,

    /// 400 kHz
    Fast,

    /// FastMode+
    #[cfg(any(ra4l1, ra6m5))]
    FastModePlus,
}

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

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

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

/// [`I2c`] driver 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 RX_INTERRUPT_EVENT: InterruptEvent;
    const TE_INTERRUPT_EVENT: InterruptEvent;
    const TX_INTERRUPT_EVENT: InterruptEvent;

    fn regs() -> pac::iic::Iic;

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

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

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

    /// # Returns
    /// Static [`RingBuffer`] for outgoing data.
    fn tx_buffer() -> &'static RingBuffer;
}

/// GPIO pin connected to the `SCL` line of an [`I2c`] instance.
#[allow(private_bounds)]
pub trait SclPin<I: Instance>: SealedSclPin<I> {}

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

    #[inline(always)]
    fn set_as_scl(&self) {
        trace!("P{}{:02}: SclPin::new", self.port(), self.pin());
        self.set_as_pf(Self::PERIPHERAL_FUNC);
    }
}

/// GPIO pin connected to the `SDA` line of an [`I2c`] instance.
#[allow(private_bounds)]
pub trait SdaPin<I: Instance>: SealedSdaPin<I> {}

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

    #[inline(always)]
    fn set_as_sda(&self) {
        trace!("P{}{:02}: SdaPin::new", self.port(), self.pin());
        self.set_as_pf(Self::PERIPHERAL_FUNC);
    }
}

impl From<Divider> for Cks {
    fn from(value: Divider) -> Self {
        Self::from_bits(value as u8)
    }
}

macro_rules! instance_impl {
    ($instance:ident, $rx_int:ident, $te_int:ident, $tx_int:ident) => {
        paste::paste! {
            impl crate::i2c::Instance for crate::peripherals::$instance {}
            impl crate::i2c::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(always)]
                fn regs() -> pac::iic::Iic {
                    // Safety:
                    // This is safe because we know the different type
                    // only adds extra registers that we don't use.
                    let instance_ptr = crate::pac::$instance.as_ptr();
                    unsafe { crate::pac::iic::Iic::from_ptr(instance_ptr) }
                }

                /// Waker for incoming data events.
                fn rx_waker() -> &'static embassy_sync::waitqueue::AtomicWaker {
                    static RX_WAKER: embassy_sync::waitqueue::AtomicWaker = embassy_sync::waitqueue::AtomicWaker::new();
                    &RX_WAKER
                }

                /// Waker for "transmit end" events.
                fn te_waker() -> &'static embassy_sync::waitqueue::AtomicWaker {
                    static TE_WAKER: embassy_sync::waitqueue::AtomicWaker = embassy_sync::waitqueue::AtomicWaker::new();
                    &TE_WAKER
                }

                /// Waker for transmit buffer empty events.
                fn tx_waker() -> &'static embassy_sync::waitqueue::AtomicWaker {
                    static TX_WAKER: embassy_sync::waitqueue::AtomicWaker = embassy_sync::waitqueue::AtomicWaker::new();
                    &TX_WAKER
                }

                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
                }
            }
        }
    };
}
pub(crate) use instance_impl;

impl<'d, I: Instance> I2c<'d, I, Blocking> {
    /// Creates a new blocking `I2c` driver.
    ///
    /// # Arguments
    /// * `iic` An [`IIC`](trait@Instance) peripheral.
    /// * `scl` A [`Pin`] that can be connected to the [clock line](trait@SclPin).
    /// * `sda` A [`Pin`] that can be connected to the [data line](trait@SdaPin).
    /// * `speed` Bitrate.
    ///
    /// # Notes
    /// The `RA4M1` does not provide any pull-up resistors for use with `I2C`.
    /// The exact speeds you will see depend on the capacitive load and resistors used.
    #[inline]
    pub fn new_blocking<C: SclPin<I>, D: SdaPin<I>>(
        iic: Peri<'d, I>,
        scl: Peri<'d, C>,
        sda: Peri<'d, D>,
        speed: I2cSpeed,
    ) -> Self {
        Self::new_inner(iic, scl, sda, speed, Blocking {})
    }

    fn blocking_read(&self, address: u8, data: &mut [u8]) -> Result<(), I2cError> {
        let iic = I::regs();
        let r_addr = (address << 1) | 0x01;
        let data_len = data.len();

        while iic.iccr2().read().bbsy() {
            asm::nop();
        }

        iic.iccr2().modify(|r| r.set_st(true));

        while !iic.icsr2().read().tdre() {
            asm::nop();
        }

        iic.icdrt().write_value(r_addr);

        let mut status = iic.icsr2().read();
        while !status.rdrf() {
            if status.nackf() {
                iic.iccr2().modify(|r| r.set_sp(true));
                return Err(I2cError::Nack);
            }
            asm::nop();
            status = iic.icsr2().read();
        }

        // Required dummy read
        let _ = iic.icdrr().read();

        for (i, byte) in data.iter_mut().enumerate() {
            if i == (data_len - 1) {
                iic.icmr3().protected_modify(|r| r.set_ackbt(true));
            }
            while !iic.icsr2().read().rdrf() {
                asm::nop();
            }
            *byte = iic.icdrr().read();
        }

        while !iic.icsr2().read().rdrf() {
            asm::nop();
        }

        iic.iccr2().modify(|r| r.set_sp(true));

        // Required dummy read
        let _ = iic.icdrr().read();

        while !iic.icsr2().read().stop() {
            asm::nop()
        }

        iic.icmr3().modify(|r| r.set_wait(false));
        iic.icsr2().modify(|r| r.set_stop(false));

        Ok(())
    }

    fn blocking_write(&self, address: u8, data: &[u8]) -> Result<(), I2cError> {
        let iic = I::regs();

        // info!("write! addr={:02x}, len={}", address, data.len());

        let w_addr = (address << 1) | 0x00;

        while iic.iccr2().read().bbsy() {
            asm::nop();
        }
        iic.iccr2().modify(|r| r.set_st(true));

        while !iic.icsr2().read().tdre() {
            if iic.icsr2().read().nackf() {
                return Err(I2cError::Nack);
            }
            asm::nop();
        }

        iic.icdrt().write_value(w_addr);
        while !iic.icsr2().read().tdre() {
            asm::nop();
        }

        if iic.icsr2().read().nackf() {
            iic.iccr2().modify(|r| r.set_sp(true));
            return Err(I2cError::Nack);
        }

        for byte in data.iter() {
            while !iic.icsr2().read().tdre() {
                asm::nop();
            }
            iic.icdrt().write_value(*byte);
        }

        while !iic.icsr2().read().tend() {
            asm::nop();
        }

        iic.iccr2().modify(|r| r.set_sp(true));

        while !iic.icsr2().read().stop() {
            asm::nop();
        }

        iic.icsr2().modify(|r| {
            r.set_stop(false);
            r.set_nackf(false);
        });

        Ok(())
    }
}

impl<'d, I: Instance, RxInt: InterruptType, TxDtc: DtcInstance> I2c<'d, I, Dtc<RxInt, TxDtc>> {
    /// Creates a new asynchronous, [`DTC`](module@crate::dtc) driven `I2c` driver.
    ///
    /// # Arguments
    /// * `iic` An [`IIC`](trait@Instance) peripheral.
    /// * `scl` A [`Pin`] that can be connected to the [clock line](trait@SclPin).
    /// * `sda` A [`Pin`] that can be connected to the [data line](trait@SdaPin).
    /// * `speed` Bitrate.
    /// * `tx_dtc` DTC peripheral for transmission.
    /// * `irqs` interrupts bound with the [`bind_interrupts!`](crate::bind_interrupts) macro.
    ///
    /// # Notes
    /// This uses DTC for transmission and interrupts for reception.
    /// Due to limitations with the `IIC` peripheral DMA/DTC reception offers little, if any, benefit.
    pub fn new_dtc<C: SclPin<I>, D: SdaPin<I>>(
        iic: Peri<'d, I>,
        scl: Peri<'d, C>,
        sda: Peri<'d, D>,
        speed: I2cSpeed,
        tx_dtc: Peri<'d, TxDtc>,
        irqs: impl interrupt::typelevel::Binding<RxInt, RxInterruptHandler<I>>
        + interrupt::typelevel::Binding<TxDtc::Int, DtcInterruptHandler<TxDtc>>
        + Clone
        + 'd,
    ) -> Self {
        let tx_dtc = DtcChannel::new(tx_dtc, irqs);
        let dtc = Dtc {
            tx_dtc,
            rx_dtc: PhantomData,
        };

        Self::new_inner(iic, scl, sda, speed, dtc)
    }

    async fn dtc_write(&mut self, address: u8, data: &[u8]) -> Result<usize, I2cError> {
        let iic = I::regs();

        if data.is_empty() {
            return Ok(0);
        }

        let w_addr = (address << 1) | 0x00;

        while iic.iccr2().read().bbsy() {}

        iic.icsr2().modify(|r| {
            r.set_start(false);
            r.set_stop(false);
        });

        iic.icier().write(|r| {
            r.set_stie(true);
            r.set_spie(true);
            r.set_tie(true);
        });

        let addr = [w_addr];

        let tx1 = self
            .mode
            .tx_dtc
            .prepare_write(&addr, iic.icdrt().as_ptr() as *mut _, false);
        let tx2 = self
            .mode
            .tx_dtc
            .prepare_write(data, iic.icdrt().as_ptr() as *mut _, true);
        let chain = [tx1, tx2];

        // Safety: The address buffer, data buffer, and the register should outlive the transfer.
        let tx = unsafe { self.mode.tx_dtc.write_chain(&chain, I::TX_INTERRUPT_EVENT) };

        iic.iccr2().modify(|r| r.set_st(true));

        tx.await.expect("DTC transfer failed");

        // This shouldn't take long and isn't worth the overhead of an interrupt
        while !iic.icsr2().read().tend() {}

        // Reading `tend` will not clear it, but a stop condition will.
        iic.iccr2().modify(|r| r.set_sp(true));

        while !iic.icsr2().read().stop() {}

        iic.icsr2().modify(|r| {
            r.set_stop(false);
            r.set_nackf(false);
        });

        Ok(addr.len())
    }

    async fn dtc_read(&self, address: u8, data: &mut [u8]) -> Result<(), I2cError> {
        let iic = I::regs();
        let r_addr = (address << 1) | 0x01;
        let data_len = data.len();

        iic.icier().write(|r| r.set_rie(true));

        while iic.iccr2().read().bbsy() {
            asm::nop();
        }

        iic.iccr2().modify(|r| r.set_st(true));

        while !iic.icsr2().read().tdre() {
            asm::nop();
        }

        iic.icdrt().write_value(r_addr);

        let mut status = iic.icsr2().read();
        while !status.rdrf() {
            if status.nackf() {
                iic.iccr2().modify(|r| r.set_sp(true));
                return Err(I2cError::Nack);
            }
            asm::nop();
            status = iic.icsr2().read();
        }

        // Required dummy read
        let _ = iic.icdrr().read();

        for (i, byte) in data.iter_mut().enumerate() {
            if i == (data_len - 1) {
                iic.icmr3().protected_modify(|r| r.set_ackbt(true));
            }

            *byte = poll_fn(|cx| {
                if iic.icsr2().read().rdrf() {
                    let byte = iic.icdrr().read();
                    Poll::Ready(byte)
                } else {
                    I::rx_waker().register(cx.waker());
                    Poll::Pending
                }
            })
            .await;
        }

        poll_fn(|cx| {
            if iic.icsr2().read().rdrf() {
                Poll::Ready(())
            } else {
                I::rx_waker().register(cx.waker());
                Poll::Pending
            }
        })
        .await;

        iic.iccr2().modify(|r| r.set_sp(true));

        // Required dummy read
        let _ = iic.icdrr().read();

        while !iic.icsr2().read().stop() {
            asm::nop()
        }

        iic.icmr3().modify(|r| r.set_wait(false));
        iic.icsr2().modify(|r| r.set_stop(false));

        iic.icier().write(|r| r.set_rie(false));

        Ok(())
    }
}

impl<'d, I: Instance, RxInt: InterruptType, TeInt: InterruptType, TxInt: InterruptType>
    I2c<'d, I, Async<RxInt, TeInt, TxInt>>
{
    /// Creates a new asynchronous, interrupt driven `I2c` driver.
    ///
    /// # Arguments
    /// * `iic` An [`IIC`](trait@Instance) peripheral.
    /// * `scl` A [`Pin`] that can be connected to the [clock line](trait@SclPin).
    /// * `sda` A [`Pin`] that can be connected to the [data line](trait@SdaPin).
    /// * `speed` Bitrate.
    /// * `tx_buffer` Transmit buffer.
    /// * `irqs` interrupts bound with the [`bind_interrupts!`](crate::bind_interrupts) macro.
    pub fn new_async<C: SclPin<I>, D: SdaPin<I>>(
        iic: Peri<'d, I>,
        scl: Peri<'d, C>,
        sda: Peri<'d, D>,
        speed: I2cSpeed,
        tx_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,
    ) -> Self {
        let _ = irqs;
        let tx_len = tx_buffer.len();

        // Safety: Caller defines the backing store for the ring buffer and the borrow checker
        //         should ensure that it remains in place as long as we need.
        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 in NVIC
            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);
        }

        let iic_regs = I::regs();

        iic_regs.icier().modify(|r| {
            r.set_tie(true);
            r.set_teie(false);
        });

        TeInt::IRQ.icu_unpend();
        TxInt::IRQ.icu_unpend();

        Self::new_inner(
            iic,
            scl,
            sda,
            speed,
            Async {
                _rx: PhantomData,
                _te: PhantomData,
                _tx: PhantomData,
            },
        )
    }

    async fn write(&self, address: u8, data: &[u8]) -> Result<usize, I2cError> {
        let iic = I::regs();

        if data.is_empty() {
            return Ok(0);
        }

        let w_addr = (address << 1) | 0x00;

        while iic.iccr2().read().bbsy() {}

        iic.icsr2().modify(|r| {
            r.set_start(false);
            r.set_stop(false);
        });

        iic.icier().write(|r| {
            r.set_stie(true);
            r.set_spie(true);
            r.set_tie(true);
        });

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

        let out = writer.push_slice();
        if out.is_empty() {
            error!("{}TX buffer is full", I::PERIPHERAL);
        }
        out[0] = w_addr;
        writer.push_done(1);
        let mut started = false;

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

                if I::tx_buffer().is_full() {
                    debug!("{}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)]);

                writer.push_done(chunk_len);

                written += chunk_len;

                if !started {
                    // TODO: § 29.17.2
                    // if TxInt::IRQ.icu_is_pending() {
                    //     iic.iccr1().modify(r| r.set_ice(false));
                    //     iic.icier().modify(r| r.set_tie(false));
                    //     while iic.icier().read().tie() {
                    //         asm::nop();
                    //     }
                    //     TxInt::IRQ.unpend();
                    //     TxInt::IRQ.icu_unpend();
                    // }

                    started = true;
                    iic.iccr2().modify(|r| r.set_st(true));
                }

                if written < data.len() {
                    return Poll::Pending;
                }

                // If there's nothing else wait on the Transmit End interrupt
                I::te_waker().register(cx.waker());

                if !iic.icsr2().read().tend() {
                    return Poll::Pending;
                }
            } else {
                I::te_waker().register(cx.waker());

                if !iic.icsr2().read().tend() {
                    return Poll::Pending;
                }
            }

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

        // Reading `tend` will not clear it, but a stop condition will.
        iic.iccr2().modify(|r| r.set_sp(true));

        while !iic.icsr2().read().stop() {}

        iic.icsr2().modify(|r| {
            r.set_stop(false);
            r.set_nackf(false);
        });

        Ok(ret)
    }

    async fn read_byte(&self) -> u8 {
        let iic = I::regs();

        poll_fn(|cx| {
            if iic.icsr2().read().rdrf() {
                let byte = iic.icdrr().read();
                Poll::Ready(byte)
            } else {
                I::rx_waker().register(cx.waker());
                Poll::Pending
            }
        })
        .await
    }

    async fn read(&self, address: u8, data: &mut [u8]) -> Result<(), I2cError> {
        let iic = I::regs();
        let r_addr = (address << 1) | 0x01;
        let data_len = data.len();

        iic.icier().write(|r| r.set_rie(true));

        while iic.iccr2().read().bbsy() {
            asm::nop();
        }

        iic.iccr2().modify(|r| r.set_st(true));

        while !iic.icsr2().read().tdre() {
            asm::nop();
        }

        iic.icdrt().write_value(r_addr);

        let mut status = iic.icsr2().read();
        while !status.rdrf() {
            if status.nackf() {
                iic.iccr2().modify(|r| r.set_sp(true));
                return Err(I2cError::Nack);
            }
            asm::nop();
            status = iic.icsr2().read();
        }

        // Required dummy read
        let _ = iic.icdrr().read();

        for (i, byte) in data.iter_mut().enumerate() {
            if i == (data_len - 1) {
                iic.icmr3().protected_modify(|r| r.set_ackbt(true));
            }

            *byte = self.read_byte().await;
        }

        poll_fn(|cx| {
            if iic.icsr2().read().rdrf() {
                Poll::Ready(())
            } else {
                I::rx_waker().register(cx.waker());
                Poll::Pending
            }
        })
        .await;

        iic.iccr2().modify(|r| r.set_sp(true));

        // Required dummy read
        let _ = iic.icdrr().read();

        while !iic.icsr2().read().stop() {
            asm::nop()
        }

        iic.icmr3().modify(|r| r.set_wait(false));
        iic.icsr2().modify(|r| r.set_stop(false));

        iic.icier().write(|r| r.set_rie(false));

        Ok(())
    }
}

#[allow(private_bounds)]
impl<'d, I: Instance, M: TransferMode> I2c<'d, I, M> {
    #[inline]
    fn new_inner<C: SclPin<I>, D: SdaPin<I>>(
        iic: Peri<'d, I>,
        scl: Peri<'d, C>,
        sda: Peri<'d, D>,
        speed: I2cSpeed,
        mode: M,
    ) -> Self {
        let clock_config = crate::clock::clock_status();

        #[rustfmt::skip]
        let clk_config = match clock_config.peripheral_b.to_MHz(){
            24 => {
                [
                    ClockConfig { divider: Divider::Div4, low: 25, high: 24 },
                    ClockConfig { divider: Divider::Div1, low: 24, high: 16 },
                ]
            },
            32 => {
                [
                    ClockConfig { divider: Divider::Div8, low: 15, high: 13 },
                    ClockConfig { divider: Divider::Div2, low: 18, high: 9 },
                ]
            }
            40 => {
                warn!("Uh this isn't right");
                [
                    ClockConfig { divider: Divider::Div4, low: 25, high: 24 },
                    ClockConfig { divider: Divider::Div1, low: 24, high: 16 },
                ]
            },
            _ => unimplemented!()
        };

        let config = match speed {
            // Tlow ≥ 4.7 µs, Thigh ≥ 4.0 µs, UM10204 Table 11
            I2cSpeed::Normal => clk_config[0],
            // Tlow ≥ 1.3 µs, Thigh ≥ 0.6 µs, UM10204 Table 11
            I2cSpeed::Fast => clk_config[1],
            #[cfg(any(ra4l1, ra6m5))]
            I2cSpeed::FastModePlus => todo!(),
        };

        Self::new_with_clock_config(iic, scl, sda, config, mode)
    }
    /// Creates a new blocking `I2c` driver with specific clock timing.
    /// # Arguments
    /// * `iic` An [`IIC`](trait@Instance) peripheral.
    /// * `scl` A [`Pin`] that can be connected to the [clock line](trait@SclPin).
    /// * `sda` A [`Pin`] that can be connected to the [data line](trait@SdaPin).
    /// * `clocks` Clock configuration.
    ///
    /// # Notes
    /// From UM10204, Table 11.
    /// For normal mode, aim for: Tlow ≥ 4.7 µs, Thigh ≥ 4.0 µs.
    /// For fast mode, aim for: Tlow ≥ 1.3 µs, Thigh ≥ 0.6 µs.
    fn new_with_clock_config<C: SclPin<I>, D: SdaPin<I>>(
        iic: Peri<'d, I>,
        scl: Peri<'d, C>,
        sda: Peri<'d, D>,
        clocks: ClockConfig,
        mode: M,
    ) -> Self {
        let _ = iic;
        I::start_module();

        let iic = I::regs();

        iic.iccr1().write(|r| r.set_ice(false));
        iic.iccr1().modify(|r| r.set_iicrst(true));
        iic.iccr1().modify(|r| r.set_ice(true));

        iic.icmr1().modify(|r| r.set_cks(clocks.divider.into()));

        // Use modify here because chiptool doesn't respect the reset values
        // Lifted these from the arduino library.
        iic.icbrl().modify(|r| r.set_brl(clocks.low));
        iic.icbrh().modify(|r| r.set_brh(clocks.high));

        iic.iccr1().modify(|r| r.set_iicrst(false));

        // p826
        // Do not assign the SCLn or SDAn pin to the IIC when setting up the pin function control.
        // Slave address comparison is performed if the pins are assigned to the IIC.
        scl.set_as_scl();
        sda.set_as_sda();

        Self {
            _instance: PhantomData,
            mode,
            _scl: Flex::new(scl),
            _sda: Flex::new(sda),
        }
    }
}

impl<RxInt: InterruptType, TeInt: InterruptType, TxInt: InterruptType> Drop
    for Async<RxInt, TeInt, TxInt>
{
    fn drop(&mut self) {
        RxInt::IRQ.icu_disable();
        TeInt::IRQ.icu_disable();
        TxInt::IRQ.icu_disable();
    }
}

impl<RxInt: InterruptType, TxDtc: DtcInstance> Drop for Dtc<RxInt, TxDtc> {
    fn drop(&mut self) {
        RxInt::IRQ.icu_disable();
        TxDtc::Int::IRQ.dtc_disable();
    }
}

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

macro_rules! scl_pin {
    ($instance:ident, $pin:ident, $pfunc:ident) => {
        impl crate::i2c::SclPin<crate::peripherals::$instance> for crate::peripherals::$pin {}
        impl crate::i2c::SealedSclPin<crate::peripherals::$instance> for crate::peripherals::$pin {
            const PERIPHERAL_FUNC: crate::gpio::PortFunction = crate::gpio::PortFunction::$pfunc;
        }
    };
}
pub(crate) use scl_pin;

macro_rules! sda_pin {
    ($instance:ident, $pin:ident, $pfunc:ident) => {
        impl crate::i2c::SdaPin<crate::peripherals::$instance> for crate::peripherals::$pin {}
        impl crate::i2c::SealedSdaPin<crate::peripherals::$instance> for crate::peripherals::$pin {
            const PERIPHERAL_FUNC: crate::gpio::PortFunction = crate::gpio::PortFunction::$pfunc;
        }
    };
}
pub(crate) use sda_pin;

/// I2C error.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum I2cError {
    /// Arbitration lost
    Arbitration,

    /// ACK not received (either to the address or to a data byte)
    Nack,

    /// Overrun error
    Overrun,
}

impl core::fmt::Display for I2cError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let message = match self {
            Self::Arbitration => "Arbitration Lost",
            Self::Nack => "ACK Not Received",
            Self::Overrun => "Buffer Overrun",
        };

        write!(f, "{}", message)
    }
}

impl core::error::Error for I2cError {}

impl embedded_hal_1::i2c::Error for I2cError {
    fn kind(&self) -> embedded_hal_1::i2c::ErrorKind {
        match *self {
            Self::Arbitration => embedded_hal_1::i2c::ErrorKind::ArbitrationLoss,
            Self::Nack => embedded_hal_1::i2c::ErrorKind::NoAcknowledge(
                embedded_hal_1::i2c::NoAcknowledgeSource::Unknown,
            ),
            Self::Overrun => embedded_hal_1::i2c::ErrorKind::Overrun,
        }
    }
}

impl<'d, I: Instance, M: TransferMode> embedded_hal_1::i2c::ErrorType for I2c<'d, I, M> {
    type Error = I2cError;
}

impl<'d, I: Instance> embedded_hal_1::i2c::I2c<SevenBitAddress> for I2c<'d, I, Blocking> {
    fn transaction(
        &mut self,
        address: u8,
        operations: &mut [embedded_hal_1::i2c::Operation<'_>],
    ) -> Result<(), Self::Error> {
        for op in operations.iter_mut() {
            match op {
                embedded_hal_1::i2c::Operation::Read(buffer) => {
                    self.blocking_read(address, buffer)?;
                }
                embedded_hal_1::i2c::Operation::Write(data) => {
                    self.blocking_write(address, data)?;
                }
            }
        }

        Ok(())
    }
}

impl<'d, I: Instance, RxInt: InterruptType, TeInt: InterruptType, TxInt: InterruptType>
    embedded_hal_async::i2c::I2c for I2c<'d, I, Async<RxInt, TeInt, TxInt>>
{
    async fn transaction(
        &mut self,
        address: u8,
        operations: &mut [embedded_hal_1::i2c::Operation<'_>],
    ) -> Result<(), Self::Error> {
        for op in operations.iter_mut() {
            match op {
                embedded_hal_1::i2c::Operation::Read(buffer) => {
                    I2c::read(self, address, buffer).await?;
                }
                embedded_hal_1::i2c::Operation::Write(data) => {
                    I2c::write(self, address, data).await?;
                }
            }
        }

        Ok(())
    }
}

impl<'d, I: Instance, RxInt: InterruptType, TxDtc: DtcInstance> embedded_hal_async::i2c::I2c
    for I2c<'d, I, Dtc<RxInt, TxDtc>>
{
    async fn transaction(
        &mut self,
        address: u8,
        operations: &mut [embedded_hal_1::i2c::Operation<'_>],
    ) -> Result<(), Self::Error> {
        for op in operations.iter_mut() {
            match op {
                embedded_hal_1::i2c::Operation::Read(buffer) => {
                    I2c::dtc_read(self, address, buffer).await?;
                }
                embedded_hal_1::i2c::Operation::Write(data) => {
                    I2c::dtc_write(self, address, data).await?;
                }
            }
        }

        Ok(())
    }
}

impl<I: Instance, TeInt: InterruptType> InterruptHandler<TeInt> for TeInterruptHandler<I> {
    // Table 29.10, note 4 admonishes us to clear `tend` here, but since we set a stop
    // condition after the waker is awoken this should be okay.
    unsafe fn on_interrupt() {
        trace!("{}TeInt", I::PERIPHERAL);
        TeInt::IRQ.icu_unpend();
        let iic = I::regs();
        iic.icier().modify(|r| r.set_teie(false));
        I::te_waker().wake();
    }
}

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

        let iic = I::regs();
        let mut tx_reader = unsafe { I::tx_buffer().reader() };
        let out_buf = tx_reader.pop_slice();
        let out_len = out_buf.len();

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

            return;
        }

        iic.icdrt().write_value(out_buf[0]);

        tx_reader.pop_done(1);

        if out_len == 1 {
            iic.icier().modify(|r| {
                r.set_tie(false);
                r.set_teie(true);
            });
            return;
        }

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

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

        RxInt::IRQ.icu_unpend();

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