rp2350 0.1.0

Hardware Abstraction Layer for RP2350 microcontrollers
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
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
//! DMA (Direct Memory Access) HAL for RP2350
//!
//! This module provides a type-safe, builder-pattern interface to the RP2350
//! DMA controller, supporting all 16 independent channels with configurable
//! transfers between memory and peripherals.
//!
//! # Architecture
//!
//! ```text
//!                    ┌─────────────────────────────────────────┐
//!                    │           DMA Controller                │
//!                    │                                         │
//!   ┌──────────┐    │  ┌────────┐ ┌────────┐           ×16  │
//!   │  Memory  │◄──►│  │  Ch 0  │ │  Ch 1  │  ...           │
//!   └──────────┘    │  │ rd/wr  │ │ rd/wr  │                │
//!                    │  │ count  │ │ count  │                │
//!   ┌──────────┐    │  │ ctrl   │ │ ctrl   │                │
//!   │  UART    │◄──►│  └────────┘ └────────┘                │
//!   └──────────┘    │                                         │
//!                    │  ┌──────────┐  ┌───────────┐           │
//!   ┌──────────┐    │  │  Sniff   │  │  Pacing   │           │
//!   │  SPI     │◄──►│  │  (CRC)   │  │  Timers   │           │
//!   └──────────┘    │  └──────────┘  └───────────┘           │
//!                    └─────────────────────────────────────────┘
//! ```
//!
//! # Builder Pattern
//!
//! A [`Channel`] is a zero-sized `Copy` handle. Every setter returns `Self`,
//! so configuration can be chained fluently *or* stored in a variable:
//!
//! ```ignore
//! ch.set_data_size(DataSize::Word)
//!     .set_treq_sel(TreqSel::Permanent)
//!     .set_incr_read(true)
//!     .set_incr_write(true)
//!     .set_addrs(src, dst)
//!     .set_trans_count(4)
//!     .trigger()
//!     .wait();
//! ```
//!
//! # Transfer Modes
//!
//! - **Memory-to-Memory**: Use [`TreqSel::Permanent`] for maximum throughput
//! - **Memory-to-Peripheral (TX)**: Paced by peripheral DREQ (e.g. UART TX FIFO)
//! - **Peripheral-to-Memory (RX)**: Paced by peripheral DREQ (e.g. UART RX FIFO)
//!
//! # Ownership & completion
//!
//! [`Dma`] owns the DMA peripheral; [`Channel`] handles are borrowed from it
//! (`dma.channel::<0>()`) and can never outlive the controller.
//!
//! [`Channel::wait`] blocks until the channel's `BUSY` flag goes high (the
//! transfer has started) and then low (it has finished). For a **paced**
//! (DREQ) transfer this also waits for the pacing peripheral to start; if it
//! never does, `wait()` blocks forever. Use interrupts
//! ([`Dma::enable_irq0`]) for paced transfers that must not block.
//!
//! # Example — Memory-to-Memory
//!
//! ```ignore
//! use rp2350::dma::{Dma, DataSize, TreqSel};
//!
//! let dma = Dma::init(dp.DMA);
//! let ch = dma.channel::<0>();
//!
//! let src = [1u32, 2, 3, 4];
//! let mut dst = [0u32; 4];
//!
//! ch.mem_to_mem(
//!     src.as_ptr() as u32,
//!     dst.as_mut_ptr() as u32,
//!     src.len() as u32,
//!     DataSize::Word,
//! )
//! .trigger()
//! .wait();
//! ```
//!
//! # Example — UART TX via DMA
//!
//! ```ignore
//! use rp2350::dma::{Dma, DataSize};
//! use rp2350::uart::Uart0;
//!
//! let dma = Dma::init(dp.DMA);
//! let ch = dma.channel::<0>();
//!
//! uart.enable_dma_tx();
//!
//! ch.mem_to_periph(
//!     data.as_ptr() as u32,
//!     uart.data_register_address(),
//!     data.len() as u32,
//!     Uart0::<_, _>::TX_DREQ,
//!     DataSize::Byte,
//! )
//! .trigger()
//! .wait();
//! ```

use pastey::paste;
use rp2350_pac::DMA;

use crate::Steal;
use crate::reset::Resettable;

/// Total number of DMA channels available on RP2350.
pub const NUM_CHANNELS: usize = 16;

// ============================================================================
// Enumerations
// ============================================================================

/// DMA data transfer size.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u32)]
pub enum DataSize {
    /// 8-bit (byte) transfers
    Byte = 0,
    /// 16-bit (halfword) transfers
    HalfWord = 1,
    /// 32-bit (word) transfers
    Word = 2,
}

/// DMA transfer request (DREQ) selection.
///
/// Selects the pacing source for a DMA channel. Each peripheral asserts its
/// own DREQ signal when ready for data. Use [`TreqSel::Permanent`] for
/// unpaced (maximum rate) transfers such as memory-to-memory.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u32)]
pub enum TreqSel {
    /// PIO0 TX0
    Pio0Tx0 = 0,
    /// PIO0 TX1
    Pio0Tx1 = 1,
    /// PIO0 TX2
    Pio0Tx2 = 2,
    /// PIO0 TX3
    Pio0Tx3 = 3,
    /// PIO0 RX0
    Pio0Rx0 = 4,
    /// PIO0 RX1
    Pio0Rx1 = 5,
    /// PIO0 RX2
    Pio0Rx2 = 6,
    /// PIO0 RX3
    Pio0Rx3 = 7,
    /// PIO1 TX0
    Pio1Tx0 = 8,
    /// PIO1 TX1
    Pio1Tx1 = 9,
    /// PIO1 TX2
    Pio1Tx2 = 10,
    /// PIO1 TX3
    Pio1Tx3 = 11,
    /// PIO1 RX0
    Pio1Rx0 = 12,
    /// PIO1 RX1
    Pio1Rx1 = 13,
    /// PIO1 RX2
    Pio1Rx2 = 14,
    /// PIO1 RX3
    Pio1Rx3 = 15,
    /// PIO2 TX0
    Pio2Tx0 = 16,
    /// PIO2 TX1
    Pio2Tx1 = 17,
    /// PIO2 TX2
    Pio2Tx2 = 18,
    /// PIO2 TX3
    Pio2Tx3 = 19,
    /// PIO2 RX0
    Pio2Rx0 = 20,
    /// PIO2 RX1
    Pio2Rx1 = 21,
    /// PIO2 RX2
    Pio2Rx2 = 22,
    /// PIO2 RX3
    Pio2Rx3 = 23,
    /// SPI0 TX
    Spi0Tx = 24,
    /// SPI0 RX
    Spi0Rx = 25,
    /// SPI1 TX
    Spi1Tx = 26,
    /// SPI1 RX
    Spi1Rx = 27,
    /// UART0 TX
    Uart0Tx = 28,
    /// UART0 RX
    Uart0Rx = 29,
    /// UART1 TX
    Uart1Tx = 30,
    /// UART1 RX
    Uart1Rx = 31,
    /// PWM Wrap 0
    PwmWrap0 = 32,
    /// PWM Wrap 1
    PwmWrap1 = 33,
    /// PWM Wrap 2
    PwmWrap2 = 34,
    /// PWM Wrap 3
    PwmWrap3 = 35,
    /// PWM Wrap 4
    PwmWrap4 = 36,
    /// PWM Wrap 5
    PwmWrap5 = 37,
    /// PWM Wrap 6
    PwmWrap6 = 38,
    /// PWM Wrap 7
    PwmWrap7 = 39,
    /// PWM Wrap 8
    PwmWrap8 = 40,
    /// PWM Wrap 9
    PwmWrap9 = 41,
    /// PWM Wrap 10
    PwmWrap10 = 42,
    /// PWM Wrap 11
    PwmWrap11 = 43,
    /// I2C0 TX
    I2c0Tx = 44,
    /// I2C0 RX
    I2c0Rx = 45,
    /// I2C1 TX
    I2c1Tx = 46,
    /// I2C1 RX
    I2c1Rx = 47,
    /// ADC
    Adc = 48,
    /// XIP Stream
    XipStream = 49,
    /// XIP QMI TX
    XipQmiTx = 50,
    /// XIP QMI RX
    XipQmiRx = 51,
    /// HSTX
    Hstx = 52,
    /// Coresight
    Coresight = 53,
    /// SHA256
    Sha256 = 54,
    /// Timer 0
    Timer0 = 59,
    /// Timer 1
    Timer1 = 60,
    /// Timer 2
    Timer2 = 61,
    /// Timer 3
    Timer3 = 62,
    /// Permanent request — always asserted, for unpaced transfers
    Permanent = 63,
}

/// Transfer count mode (`MODE` field, bits `[31:28]` of `TRANS_COUNT`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u32)]
pub enum TransCountMode {
    /// Normal mode — decrement count until zero, then raise IRQ
    Normal = 0,
    /// Trigger self — reload count from DBG_TCR when complete
    TriggerSelf = 1,
    /// Endless — infinite transfers, never raises completion IRQ
    Endless = 15,
}

/// Sniff (CRC / checksum) calculation type.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u32)]
pub enum SniffCalc {
    /// CRC-32 (IEEE 802.3 polynomial)
    Crc32 = 0,
    /// CRC-32 with bit-reversed data
    Crc32Rev = 1,
    /// CRC-16 CCITT
    Crc16 = 2,
    /// CRC-16 CCITT with bit-reversed data
    Crc16Rev = 3,
    /// XOR reduction (even parity)
    Even = 14,
    /// Summation
    Sum = 15,
}

// ============================================================================
// DMA Controller
// ============================================================================

/// DMA controller, owning the PAC peripheral.
///
/// Create once via [`Dma::init()`], then obtain individual [`Channel`] handles
/// via [`Dma::channel()`].
pub struct Dma {
    dma: rp2350_pac::DMA,
}

impl Dma {
    /// Initialize the DMA controller, consuming the PAC peripheral.
    ///
    /// This brings the DMA block out of reset and returns a controller
    /// from which individual channels can be obtained.
    ///
    /// # Arguments
    ///
    /// * `dma` — The DMA peripheral from `Peripherals::take()`
    pub fn init(dma: rp2350_pac::DMA) -> Self {
        // Reset then unreset to guarantee clean register state
        <rp2350_pac::DMA as Resettable>::init();
        Self { dma }
    }

    /// Obtain a Dma handle without ownership checks.
    ///
    /// # Safety
    ///
    /// The caller must ensure [`Dma::init()`] has been called first
    /// and that no data races occur.
    #[inline]
    pub unsafe fn steal() -> Steal<Self> {
        Steal(Self {
            dma: unsafe { rp2350_pac::DMA::steal() },
        })
    }

    // ========================================================================
    // Channel Access
    // ========================================================================

    /// Obtain a handle to DMA channel `N` (0–15).
    ///
    /// The returned [`Channel`] is a zero-sized handle borrowed from `self`,
    /// so it can never outlive the controller. Multiple channels can coexist
    /// simultaneously.
    ///
    /// # Panics
    ///
    /// Compile-time error if `N >= 16`.
    #[inline]
    pub const fn channel<const N: u8>(&self) -> Channel<'_, N> {
        const {
            assert!(
                (N as usize) < NUM_CHANNELS,
                "DMA channel number must be 0-15"
            )
        };
        Channel { dma: &self.dma }
    }

    // ========================================================================
    // Global DMA Register Helpers
    // ========================================================================

    #[inline]
    fn regs(&self) -> &rp2350_pac::dma::RegisterBlock {
        &self.dma
    }

    /// Report the number of DMA channels present in hardware.
    #[inline]
    pub fn num_channels(&self) -> u32 {
        self.regs().n_channels.n_channels()
    }

    // ========================================================================
    // Multi-channel Operations
    // ========================================================================

    /// Trigger several channels at once.
    ///
    /// Each set bit in `mask` triggers the corresponding channel.
    #[inline]
    pub fn trigger_channels(&self, mask: u16) {
        self.regs()
            .multi_chan_trigger
            .write_multi_chan_trigger(mask as u32);
    }

    /// Abort transfers on the channels indicated by `mask`.
    #[inline]
    pub fn abort_channels(&self, mask: u16) {
        self.regs().chan_abort.write_chan_abort(mask as u32);
    }

    // ========================================================================
    // Interrupt Control — IRQ 0
    // ========================================================================

    /// Read raw (unmasked) interrupt status for all channels.
    #[inline]
    pub fn raw_interrupts(&self) -> u16 {
        self.regs().intr.intr() as u16
    }

    /// Enable completion interrupt on IRQ 0 for the given channel.
    #[inline]
    pub fn enable_irq0(&self, channel: u8) {
        debug_assert!(channel < 16);
        self.regs().inte0.set_bits(1 << channel);
    }

    /// Disable completion interrupt on IRQ 0 for the given channel.
    #[inline]
    pub fn disable_irq0(&self, channel: u8) {
        debug_assert!(channel < 16);
        self.regs().inte0.clr_bits(1 << channel);
    }

    /// Read masked interrupt status for IRQ 0.
    #[inline]
    pub fn ints0(&self) -> u16 {
        self.regs().ints0.ints0() as u16
    }

    /// Acknowledge (clear) IRQ 0 interrupts for the given channel mask.
    #[inline]
    pub fn ack_irq0(&self, mask: u16) {
        self.regs().ints0.write_bits(mask as u32);
    }

    // ========================================================================
    // Interrupt Control — IRQ 1
    // ========================================================================

    /// Enable completion interrupt on IRQ 1 for the given channel.
    #[inline]
    pub fn enable_irq1(&self, channel: u8) {
        debug_assert!(channel < 16);
        self.regs().inte1.set_bits(1 << channel);
    }

    /// Disable completion interrupt on IRQ 1 for the given channel.
    #[inline]
    pub fn disable_irq1(&self, channel: u8) {
        debug_assert!(channel < 16);
        self.regs().inte1.clr_bits(1 << channel);
    }

    /// Read masked interrupt status for IRQ 1.
    #[inline]
    pub fn ints1(&self) -> u16 {
        self.regs().ints1.ints1() as u16
    }

    /// Acknowledge (clear) IRQ 1 interrupts for the given channel mask.
    #[inline]
    pub fn ack_irq1(&self, mask: u16) {
        self.regs().ints1.write_bits(mask as u32);
    }

    // ========================================================================
    // Pacing Timers
    // ========================================================================

    /// Configure a fractional pacing timer.
    ///
    /// The timer fires at rate: `sys_clk × numerator / denominator`.
    /// Timer index must be 0–3.
    pub fn set_timer(&self, index: u8, numerator: u16, denominator: u16) {
        let val = ((numerator as u32) << 16) | (denominator as u32);
        let regs = self.regs();
        match index {
            0 => regs.timer0.write_bits(val),
            1 => regs.timer1.write_bits(val),
            2 => regs.timer2.write_bits(val),
            3 => regs.timer3.write_bits(val),
            _ => panic!("DMA timer index must be 0-3"),
        }
    }

    // ========================================================================
    // Sniff (CRC / Checksum) Hardware
    // ========================================================================

    /// Enable or disable the sniff hardware block.
    #[inline]
    pub fn sniff_enable(&self, enable: bool) {
        if enable {
            self.regs().sniff_ctrl.set_en();
        } else {
            self.regs().sniff_ctrl.clr_en();
        }
    }

    /// Set which channel the sniff hardware monitors.
    #[inline]
    pub fn sniff_set_channel(&self, channel: u8) {
        self.regs().sniff_ctrl.write_dmach(channel as u32 & 0xF);
    }

    /// Set the sniff calculation type.
    #[inline]
    pub fn sniff_set_calc(&self, calc: SniffCalc) {
        self.regs().sniff_ctrl.write_calc(calc as u32);
    }

    /// Read the accumulated sniff result (CRC / checksum).
    #[inline]
    pub fn sniff_data(&self) -> u32 {
        self.regs().sniff_data.sniff_data()
    }

    /// Write a seed value into the sniff accumulator.
    #[inline]
    pub fn sniff_set_data(&self, seed: u32) {
        self.regs().sniff_data.write_sniff_data(seed);
    }

    /// Enable or disable byte-swap on sniff input data.
    #[inline]
    pub fn sniff_set_bswap(&self, enable: bool) {
        if enable {
            self.regs().sniff_ctrl.set_bswap();
        } else {
            self.regs().sniff_ctrl.clr_bswap();
        }
    }

    /// Enable or disable bit inversion on sniff output.
    #[inline]
    pub fn sniff_set_out_inv(&self, enable: bool) {
        if enable {
            self.regs().sniff_ctrl.set_out_inv();
        } else {
            self.regs().sniff_ctrl.clr_out_inv();
        }
    }

    /// Enable or disable bit reversal on sniff output.
    #[inline]
    pub fn sniff_set_out_rev(&self, enable: bool) {
        if enable {
            self.regs().sniff_ctrl.set_out_rev();
        } else {
            self.regs().sniff_ctrl.clr_out_rev();
        }
    }

    // ========================================================================
    // FIFO Debug Levels
    // ========================================================================

    /// Get the transfer-data FIFO level.
    #[inline]
    pub fn tdf_level(&self) -> u8 {
        self.regs().fifo_levels.tdf_lvl() as u8
    }

    /// Get the write-address FIFO level.
    #[inline]
    pub fn waf_level(&self) -> u8 {
        self.regs().fifo_levels.waf_lvl() as u8
    }

    /// Get the read-address FIFO level.
    #[inline]
    pub fn raf_level(&self) -> u8 {
        self.regs().fifo_levels.raf_lvl() as u8
    }
}

// ============================================================================
// DMA Channel
// ============================================================================

/// A single DMA channel, parameterised by channel number `N` (0–15).
///
/// A zero-sized, `Copy` handle borrowed from the owning [`Dma`] controller;
/// it can never outlive it. All setter methods return `Self` for builder
/// chaining.
///
/// # Example
///
/// ```ignore
/// let ch = dma.channel::<0>();
/// ch.disable()
///     .set_data_size(DataSize::Word)
///     .set_treq_sel(TreqSel::Permanent)
///     .set_incr_read(true)
///     .set_incr_write(true)
///     .set_addrs(src, dst)
///     .set_trans_count(count)
///     .trigger()
///     .wait();
/// ```
#[derive(Clone, Copy)]
pub struct Channel<'a, const N: u8> {
    dma: &'a DMA,
}

impl<'a, const N: u8> Channel<'a, N> {
    /// Access the shared DMA register block.
    #[inline(always)]
    fn regs(&self) -> &'a rp2350_pac::dma::RegisterBlock {
        self.dma
    }
}

// Generate per-channel implementations for all 16 channels.
// Each channel's registers are individually named in the PAC (ch0_*, ch1_*, …, ch15_*),
// so we use `paste!` to assemble the correct field / method names.
macro_rules! impl_channel {
    ($n:literal) => {
        paste! {
            impl<'a> Channel<'a, $n> {
                // ============================================================
                // Address Registers
                // ============================================================

                /// Set the source (read) address for this channel.
                #[inline]
                pub fn set_read_addr(&self, addr: u32) -> Self {
                    self.regs().[<ch $n _read_addr>].[<write_ch $n _read_addr>](addr);
                    *self
                }

                /// Get the current source (read) address.
                #[inline]
                pub fn read_addr(&self) -> u32 {
                    self.regs().[<ch $n _read_addr>].[<ch $n _read_addr>]()
                }

                /// Set the destination (write) address for this channel.
                #[inline]
                pub fn set_write_addr(&self, addr: u32) -> Self {
                    self.regs().[<ch $n _write_addr>].[<write_ch $n _write_addr>](addr);
                    *self
                }

                /// Get the current destination (write) address.
                #[inline]
                pub fn write_addr(&self) -> u32 {
                    self.regs().[<ch $n _write_addr>].[<ch $n _write_addr>]()
                }

                /// Set both read and write addresses in one call.
                #[inline]
                pub fn set_addrs(&self, read: u32, write: u32) -> Self {
                    self.set_read_addr(read);
                    self.set_write_addr(write);
                    *self
                }

                // ============================================================
                // Transfer Count
                // ============================================================

                /// Set the transfer count (number of data elements).
                #[inline]
                pub fn set_trans_count(&self, count: u32) -> Self {
                    self.regs().[<ch $n _trans_count>].write_count(count);
                    *self
                }

                /// Set the transfer count mode (normal, trigger-self, endless).
                #[inline]
                pub fn set_trans_count_mode(&self, mode: TransCountMode) -> Self {
                    self.regs().[<ch $n _trans_count>].write_mode(mode as u32);
                    *self
                }

                /// Get the remaining transfer count.
                #[inline]
                pub fn trans_count(&self) -> u32 {
                    self.regs().[<ch $n _trans_count>].count()
                }

                // ============================================================
                // Control / Status (CTRL_TRIG)
                // ============================================================

                /// Enable (start) this channel.
                #[inline]
                pub fn enable(&self) -> Self {
                    self.regs().[<ch $n _ctrl_trig>].set_en();
                    *self
                }

                /// Disable this channel.
                #[inline]
                pub fn disable(&self) -> Self {
                    self.regs().[<ch $n _ctrl_trig>].clr_en();
                    *self
                }

                /// Check whether this channel is currently transferring data.
                #[inline]
                pub fn is_busy(&self) -> bool {
                    self.regs().[<ch $n _ctrl_trig>].busy()
                }

                /// Set the transfer data-element size.
                #[inline]
                pub fn set_data_size(&self, size: DataSize) -> Self {
                    self.regs().[<ch $n _ctrl_trig>].write_data_size(size as u32);
                    *self
                }

                /// Set the DREQ pacing source.
                #[inline]
                pub fn set_treq_sel(&self, treq: TreqSel) -> Self {
                    self.regs().[<ch $n _ctrl_trig>].write_treq_sel(treq as u32);
                    *self
                }

                /// Enable or disable read-address increment.
                #[inline]
                pub fn set_incr_read(&self, incr: bool) -> Self {
                    if incr {
                        self.regs().[<ch $n _ctrl_trig>].set_incr_read();
                    } else {
                        self.regs().[<ch $n _ctrl_trig>].clr_incr_read();
                    }
                    *self
                }

                /// Enable or disable write-address increment.
                #[inline]
                pub fn set_incr_write(&self, incr: bool) -> Self {
                    if incr {
                        self.regs().[<ch $n _ctrl_trig>].set_incr_write();
                    } else {
                        self.regs().[<ch $n _ctrl_trig>].clr_incr_write();
                    }
                    *self
                }

                /// Set the chain-to channel (triggers channel `ch` on completion).
                ///
                /// Set to this channel's own number (`N`) to disable chaining.
                #[inline]
                pub fn set_chain_to(&self, ch: u8) -> Self {
                    self.regs().[<ch $n _ctrl_trig>].write_chain_to(ch as u32 & 0xF);
                    *self
                }

                /// Set the ring-buffer wrap side (read or write).
                ///
                /// * `false` — ring wraps the read address
                /// * `true` — ring wraps the write address
                #[inline]
                pub fn set_ring_sel(&self, write_side: bool) -> Self {
                    if write_side {
                        self.regs().[<ch $n _ctrl_trig>].set_ring_sel();
                    } else {
                        self.regs().[<ch $n _ctrl_trig>].clr_ring_sel();
                    }
                    *self
                }

                /// Set the ring-buffer size as log₂(bytes). 0 disables the ring.
                #[inline]
                pub fn set_ring_size(&self, log2_bytes: u8) -> Self {
                    self.regs().[<ch $n _ctrl_trig>]
                        .write_ring_size(log2_bytes as u32 & 0xF);
                    *self
                }

                /// Enable or disable high-priority scheduling.
                #[inline]
                pub fn set_high_priority(&self, high: bool) -> Self {
                    if high {
                        self.regs().[<ch $n _ctrl_trig>].set_high_priority();
                    } else {
                        self.regs().[<ch $n _ctrl_trig>].clr_high_priority();
                    }
                    *self
                }

                /// Enable or disable byte-swap on transfer data.
                #[inline]
                pub fn set_bswap(&self, enable: bool) -> Self {
                    if enable {
                        self.regs().[<ch $n _ctrl_trig>].set_bswap();
                    } else {
                        self.regs().[<ch $n _ctrl_trig>].clr_bswap();
                    }
                    *self
                }

                /// Enable or disable IRQ quiet mode.
                ///
                /// When quiet, the channel does not raise an interrupt on completion.
                #[inline]
                pub fn set_irq_quiet(&self, quiet: bool) -> Self {
                    if quiet {
                        self.regs().[<ch $n _ctrl_trig>].set_irq_quiet();
                    } else {
                        self.regs().[<ch $n _ctrl_trig>].clr_irq_quiet();
                    }
                    *self
                }

                /// Enable or disable sniff hardware on this channel.
                #[inline]
                pub fn set_sniff_en(&self, enable: bool) -> Self {
                    if enable {
                        self.regs().[<ch $n _ctrl_trig>].set_sniff_en();
                    } else {
                        self.regs().[<ch $n _ctrl_trig>].clr_sniff_en();
                    }
                    *self
                }

                // ============================================================
                // Error Handling
                // ============================================================

                /// Check for a read-bus error.
                #[inline]
                pub fn has_read_error(&self) -> bool {
                    self.regs().[<ch $n _ctrl_trig>].read_error()
                }

                /// Check for a write-bus error.
                #[inline]
                pub fn has_write_error(&self) -> bool {
                    self.regs().[<ch $n _ctrl_trig>].write_error()
                }

                /// Clear the read-bus error flag (write-1-to-clear).
                #[inline]
                pub fn clear_read_error(&self) -> Self {
                    self.regs().[<ch $n _ctrl_trig>].set_read_error();
                    *self
                }

                /// Clear the write-bus error flag (write-1-to-clear).
                #[inline]
                pub fn clear_write_error(&self) -> Self {
                    self.regs().[<ch $n _ctrl_trig>].set_write_error();
                    *self
                }

                /// Check for an AHB bus error (logical OR of read/write errors).
                #[inline]
                pub fn has_ahb_error(&self) -> bool {
                    self.regs().[<ch $n _ctrl_trig>].ahb_error()
                }

                // ============================================================
                // Alias Registers (trigger variants)
                // ============================================================

                /// Write to the Alias-1 TRANS_COUNT_TRIG register.
                ///
                /// Writing here sets the transfer count **and** triggers
                /// the channel to start.
                #[inline]
                pub fn write_trans_count_trig(&self, count: u32) -> Self {
                    self.regs().[<ch $n _al1_trans_count_trig>]
                        .[<write_ch $n _al1_trans_count_trig>](count);
                    *self
                }

                /// Write to the Alias-3 READ_ADDR_TRIG register.
                ///
                /// Writing here sets the read address **and** triggers
                /// the channel to start.
                #[inline]
                pub fn write_read_addr_trig(&self, addr: u32) -> Self {
                    self.regs().[<ch $n _al3_read_addr_trig>]
                        .[<write_ch $n _al3_read_addr_trig>](addr);
                    *self
                }

                /// Write to the Alias-2 WRITE_ADDR_TRIG register.
                ///
                /// Writing here sets the write address **and** triggers
                /// the channel to start.
                #[inline]
                pub fn write_write_addr_trig(&self, addr: u32) -> Self {
                    self.regs().[<ch $n _al2_write_addr_trig>]
                        .[<write_ch $n _al2_write_addr_trig>](addr);
                    *self
                }

                // ============================================================
                // Trigger / Wait / Abort
                // ============================================================

                /// Start (trigger) this channel by setting the EN bit.
                #[inline]
                pub fn trigger(&self) -> Self {
                    self.regs().[<ch $n _ctrl_trig>].set_en();
                    *self
                }

                /// Block until this channel's transfer completes.
                ///
                /// Waits for `BUSY` to go high (the transfer has started) and
                /// then low (it has finished). For a **paced** (DREQ) transfer,
                /// the first phase blocks until the pacing peripheral starts the
                /// transfer — if it never does, this blocks forever. Use
                /// interrupts ([`Dma::enable_irq0`]) for paced transfers that
                /// must not block.
                #[inline]
                pub fn wait(&self) -> Self {
                    while !self.is_busy() {
                        core::hint::spin_loop();
                    }
                    while self.is_busy() {
                        core::hint::spin_loop();
                    }
                    *self
                }

                /// Abort this channel's in-progress transfer.
                ///
                /// # Panics
                ///
                /// Panics if the abort does not take effect within
                /// [`crate::spin::SPIN_TIMEOUT`] iterations.
                #[inline]
                pub fn abort(&self) -> Self {
                    self.regs().chan_abort.write_chan_abort(1 << $n);
                    // Wait for abort to take effect (bounded)
                    crate::spin::spin_wait("DMA abort", || !self.is_busy());
                    *self
                }

                // ============================================================
                // Convenience — Common Transfer Patterns
                // ============================================================

                /// Set up a memory-to-memory transfer.
                ///
                /// Configures the channel for an unpaced transfer with both
                /// address pointers incrementing, and clears any leftover
                /// ring-buffer / byte-swap / endless-mode state. Does **not**
                /// start the transfer — chain `.trigger()` to begin.
                ///
                /// ```ignore
                /// ch.mem_to_mem(src, dst, 4, DataSize::Word)
                ///     .trigger()
                ///     .wait();
                /// ```
                pub fn mem_to_mem(
                    &self,
                    src: u32,
                    dst: u32,
                    count: u32,
                    data_size: DataSize,
                ) -> Self {
                    self.disable()
                        .set_data_size(data_size)
                        .set_treq_sel(TreqSel::Permanent)
                        .set_incr_read(true)
                        .set_incr_write(true)
                        .set_chain_to($n)
                        .set_trans_count_mode(TransCountMode::Normal)
                        .set_ring_size(0)
                        .set_bswap(false)
                        .set_high_priority(false)
                        .set_sniff_en(false)
                        .set_irq_quiet(false)
                        .set_addrs(src, dst)
                        .set_trans_count(count)
                }

                /// Set up a memory-to-peripheral (TX) transfer.
                ///
                /// Read pointer increments through source buffer; write pointer
                /// is fixed at the peripheral data register. Clears any leftover
                /// ring-buffer / byte-swap / endless-mode state.
                ///
                /// ```ignore
                /// ch.mem_to_periph(
                ///     data.as_ptr() as u32,
                ///     uart.data_register_address(),
                ///     data.len() as u32,
                ///     Uart0::<_, _>::TX_DREQ,
                ///     DataSize::Byte,
                /// )
                /// .trigger()
                /// .wait();
                /// ```
                pub fn mem_to_periph(
                    &self,
                    src: u32,
                    periph_addr: u32,
                    count: u32,
                    treq: TreqSel,
                    data_size: DataSize,
                ) -> Self {
                    self.disable()
                        .set_data_size(data_size)
                        .set_treq_sel(treq)
                        .set_incr_read(true)
                        .set_incr_write(false)
                        .set_chain_to($n)
                        .set_trans_count_mode(TransCountMode::Normal)
                        .set_ring_size(0)
                        .set_bswap(false)
                        .set_high_priority(false)
                        .set_sniff_en(false)
                        .set_irq_quiet(false)
                        .set_addrs(src, periph_addr)
                        .set_trans_count(count)
                }

                /// Set up a peripheral-to-memory (RX) transfer.
                ///
                /// Read pointer is fixed at the peripheral data register; write
                /// pointer increments through destination buffer. Clears any
                /// leftover ring-buffer / byte-swap / endless-mode state.
                ///
                /// ```ignore
                /// ch.periph_to_mem(
                ///     uart.data_register_address(),
                ///     buf.as_mut_ptr() as u32,
                ///     buf.len() as u32,
                ///     Uart0::<_, _>::RX_DREQ,
                ///     DataSize::Byte,
                /// )
                /// .trigger()
                /// .wait();
                /// ```
                pub fn periph_to_mem(
                    &self,
                    periph_addr: u32,
                    dst: u32,
                    count: u32,
                    treq: TreqSel,
                    data_size: DataSize,
                ) -> Self {
                    self.disable()
                        .set_data_size(data_size)
                        .set_treq_sel(treq)
                        .set_incr_read(false)
                        .set_incr_write(true)
                        .set_chain_to($n)
                        .set_trans_count_mode(TransCountMode::Normal)
                        .set_ring_size(0)
                        .set_bswap(false)
                        .set_high_priority(false)
                        .set_sniff_en(false)
                        .set_irq_quiet(false)
                        .set_addrs(periph_addr, dst)
                        .set_trans_count(count)
                }
            }
        }
    };
}

// Expand for all 16 channels
impl_channel!(0);
impl_channel!(1);
impl_channel!(2);
impl_channel!(3);
impl_channel!(4);
impl_channel!(5);
impl_channel!(6);
impl_channel!(7);
impl_channel!(8);
impl_channel!(9);
impl_channel!(10);
impl_channel!(11);
impl_channel!(12);
impl_channel!(13);
impl_channel!(14);
impl_channel!(15);