atsam4-hal 0.3.1

HAL for the ATSAM4 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
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
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
//! ADC Implementation
//! Loosely based off of <https://github.com/atsamd-rs/atsamd/blob/master/hal/src/thumbv7em/adc.rs>
//! NOTE: From ASF the following MCUs could be supported with this module
//!       (sam/drivers/adc/adc.c)
//!       atsam3s
//!       atsam3n
//!       atsam3u
//!       atsam3xa
//!       atsam4s (supported)
//!       atsam4c
//!       atsam4cp
//!       atsam4cm
//!
//! TODO
//! - Additional power saving (peripheral clock)
//! - Automatic comparison

use crate::clock::{AdcClock, Enabled};
use crate::gpio::*;
use crate::hal::adc::{Channel, OneShot};
use crate::pac::ADC;
use crate::pdc::*;
use core::marker::PhantomData;
use core::sync::atomic::{compiler_fence, Ordering};
use cortex_m::singleton;
use embedded_dma::WriteBuffer;
use fugit::RateExtU32;

#[derive(PartialEq, Eq, Copy, Clone, Debug, defmt::Format)]
pub enum Powersaving {
    /// ADC core and reference voltage circuitry are kept on between conversions
    Normal,
    /// Voltage reference is kept on, but ADC core is disabled between conversions
    FastWakeup,
    /// ADC core and voltage reference are disabled between conversions
    Sleep,
}

#[derive(PartialEq, Eq, Copy, Clone, Debug, defmt::Format)]
pub enum SingleEndedGain {
    /// Single-ended gain = 1
    Gain1x = 1,
    /// Single-ended gain = 2
    Gain2x = 2,
    /// Single-ended gain = 4
    Gain4x = 3,
}

#[derive(PartialEq, Eq, Copy, Clone, Debug, defmt::Format)]
pub enum StartupTime {
    /// 0 periods of ADCCLK
    Sut0,
    /// 8 periods of ADCCLK
    Sut8,
    /// 16 periods of ADCCLK
    Sut16,
    /// 24 periods of ADCCLK
    Sut24,
    /// 64 periods of ADCCLK
    Sut64,
    /// 80 periods of ADCCLK
    Sut80,
    /// 96 periods of ADCCLK
    Sut96,
    /// 112 periods of ADCCLK
    Sut112,
    /// 512 periods of ADCCLK
    Sut512,
    /// 576 periods of ADCCLK
    Sut576,
    /// 640 periods of ADCCLK
    Sut640,
    /// 704 periods of ADCCLK
    Sut704,
    /// 768 periods of ADCCLK
    Sut768,
    /// 832 periods of ADCCLK
    Sut832,
    /// 896 periods of ADCCLK
    Sut896,
    /// 960 periods of ADCCLK
    Sut960,
}

#[derive(PartialEq, Eq, Copy, Clone, Debug, defmt::Format)]
pub enum SettlingTime {
    /// 3 periods of ADCCLK
    Ast3,
    /// 5 periods of ADCCLK
    Ast5,
    /// 9 periods of ADCCLK
    Ast9,
    /// 17 periods of ADCCLK
    Ast17,
}

#[derive(PartialEq, Eq, Copy, Clone, Debug, defmt::Format)]
pub enum TrackingTime {
    /// 1 period of ADDCLK
    Tt1 = 0,
    /// 2 periods of ADDCLK
    Tt2 = 1,
    /// 3 periods of ADDCLK
    Tt3 = 2,
    /// 4 periods of ADDCLK
    Tt4 = 3,
    /// 5 periods of ADDCLK
    Tt5 = 4,
    /// 6 periods of ADDCLK
    Tt6 = 5,
    /// 7 periods of ADDCLK
    Tt7 = 6,
    /// 8 periods of ADDCLK
    Tt8 = 7,
    /// 9 periods of ADDCLK
    Tt9 = 8,
    /// 10 periods of ADDCLK
    Tt10 = 9,
    /// 11 periods of ADDCLK
    Tt11 = 10,
    /// 12 periods of ADDCLK
    Tt12 = 11,
    /// 13 periods of ADDCLK
    Tt13 = 12,
    /// 14 periods of ADDCLK
    Tt14 = 13,
    /// 15 periods of ADDCLK
    Tt15 = 14,
    /// 16 periods of ADDCLK
    Tt16 = 15,
}

/// Transfer time (also known as hold time)
#[derive(PartialEq, Eq, Copy, Clone, Debug, defmt::Format)]
pub enum TransferTime {
    /// 3 period of ADCCLK
    Tt3 = 0,
    /// 5 periods of ADCCLK
    Tt5 = 1,
    /// 7 periods of ADCCLK
    Tt7 = 2,
    /// 11 periods of ADCCLK
    Tt11 = 3,
}

/// An ADC where results are accessible via interrupt servicing.
/// This is based off of atsamd-hal's InterruptAdc interface.
/// It supports both single conversion and free running using an interrupt.
///
/// ```
/// use atsam4_hal::adc::Adc;
/// use atsam4_hal::clock::{ClockController, MainClock, SlowClock};
/// use atsam4_hal::pac::Peripherals;
///
/// let peripherals = Peripherals::take().unwrap();
/// let clocks = ClockController::new(
///     peripherals.PMC,
///     &peripherals.SUPC,
///     &peripherals.EFC0,
///     MainClock::Crystal12Mhz,
///     SlowClock::RcOscillator32Khz,
/// );
/// let gpio_ports = Ports::new( // ATSAM4S8B
///     (
///         peripherals.PIOA,
///         clocks.peripheral_clocks.pio_a.into_enabled_clock(),
///     ),
///     (
///         peripherals.PIOB,
///         clocks.peripheral_clocks.pio_b.into_enabled_clock(),
///     ),
/// );
/// let mut pins = Pins::new(gpio_ports, &peripherals.MATRIX)
///
/// let mut adc = Adc::new(
///     peripherals.ADC,
///     clocks.peripheral_clocks.adc.into_enabled_clock(),
/// );
/// // Channels, gain and offset must be enabled and set before starting autocalibration
/// adc.enable_channel(&mut pins.sense1); // pin sense1 = a17<ExFn, into_extra_function>
/// adc.enable_channel(&mut pins.sense2); // pin sense2 = a18<ExFn, into_extra_function>
/// adc.gain(&mut pins.sense1, SingleEndedGain::Gain4x);
/// adc.offset(&mut pins.sense1, true);
/// adc.autocalibration(true); // Waits for autocalibration to complete
///
/// // Convert to an InterruptAdc (either SingleConversion or FreeRunning)
/// let mut adc: InterruptAdc<FreeRunning> = InterruptAdc::from(adc);
/// // NOTE: You must both enable the channel and start the conversion for each pin
/// //       Enabling the pins will start sampling; however, you must call start_conversion
/// //       in order to enable the interrupt.
/// adc.start_conversion(&mut pins.sense1);
/// adc.start_conversion(&mut pins.sense2);
///
/// // RTIC interrupt. adc, sense1 and sense2 are the resource
/// #[task(binds = ADC, resources = [adc, sense1, sense2])]
/// fn adc(cx: adc::Context) {
///     if let Some(values) = cx.resources.adc.service_interrupt_ready(cx.resources.sense1) {
///         defmt::trace!("CH0 {}", values);
///     }
///     if let Some(values) = cx.resources.adc.service_interrupt_ready(cx.resources.sense2) {
///         defmt::trace!("CH1 {}", values);
///     }
/// }
/// ```
pub struct InterruptAdc<C>
where
    C: ConversionMode,
{
    adc: Adc,
    m: core::marker::PhantomData<C>,
}

/// Single shot ADC conversions
/// Implements the embedded-hal ADC OneShot interface
///
/// ```
/// use atsam4_hal::adc::Adc;
/// use atsam4_hal::clock::{ClockController, MainClock, SlowClock};
/// use atsam4_hal::pac::Peripherals;
///
/// let peripherals = Peripherals::take().unwrap();
/// let clocks = ClockController::new(
///     peripherals.PMC,
///     &peripherals.SUPC,
///     &peripherals.EFC0,
///     MainClock::Crystal12Mhz,
///     SlowClock::RcOscillator32Khz,
/// );
/// let gpio_ports = Ports::new(
///     (
///         peripherals.PIOA,
///         clocks.peripheral_clocks.pio_a.into_enabled_clock(),
///     ),
///     (
///         peripherals.PIOB,
///         clocks.peripheral_clocks.pio_b.into_enabled_clock(),
///     ),
/// );
/// let mut pins = Pins::new(gpio_ports, &peripherals.MATRIX)
///
/// let mut adc = Adc::new(
///     peripherals.ADC,
///     clocks.peripheral_clocks.adc.into_enabled_clock(),
/// );
/// // Channels, gain and offset must be enabled and set before starting autocalibration
/// adc.enable_channel(&mut pins.sense1); // pin sense1 = a17<ExFn, into_extra_function>
/// adc.gain(&mut pins.sense1, SingleEndedGain::Gain4x);
/// adc.offset(&mut pins.sense1, true);
/// adc.autocalibration(true); // Waits for autocalibration to complete
///
/// // Read a single value from the ADC channel
/// let _value: u16 = adc.read(pins.sense1).unwrap();
/// ```
pub struct Adc {
    adc: ADC,
    clock: PhantomData<AdcClock<Enabled>>,
}

pub struct SingleConversion;
pub struct FreeRunning;

/// Describes how an interrupt-driven ADC should finalize the peripheral
/// when the conversion completes.
pub trait ConversionMode {
    fn on_start(adc: &mut Adc);
    fn on_complete<PIN: Channel<ADC, ID = u8>>(adc: &mut Adc, pin: &mut PIN);
    fn on_stop<PIN: Channel<ADC, ID = u8>>(adc: &mut Adc, pin: &mut PIN);
}

impl Adc {
    /// Default ADC initialization using 20 MHz ADC clock
    /// Uses typical configuration.
    pub fn new(adc: ADC, clock: AdcClock<Enabled>) -> Self {
        // Clear ADC write-protect
        adc.wpmr
            .modify(|_, w| w.wpkey().passwd().wpen().clear_bit());

        /*
         * Formula: ADCClock = MCK / ((PRESCAL+1) * 2)
         *  MCK = 120MHz, PRESCAL = 2, then:
         *  ADCClock = 120 / ((2+1) * 2) = 20MHz;
         *  sam4s max ADCClock = 22 MHz
         *
         * Formula:
         *     Startup  Time = startup value / ADCClock
         *     Startup time = 64 / 20MHz = 3.2 us (4)
         *     Startup time = 80 / 20MHz = 4 us (5)
         *     Startup time = 96 / 20MHz = 4.8 us (6)
         *     Startup time = 112 / 20MHz = 5.6 us (7)
         *     Startup time = 512 / 20MHz = 25.6 us (8)
         *     sam4s Min Startup Time = 4 us (max 12 us)
         *
         * adc_init(ADC, sysclk_get_cpu_hz(), 20000000, ADC_STARTUP_TIME_5);
         */
        unsafe {
            // Reset the controller (simulates hardware reset)
            adc.cr.write_with_zero(|w| w.swrst().set_bit());

            // Reset mode register (set all fields to 0)
            adc.mr.write_with_zero(|w| w);

            // Reset PDC transfer
            adc.ptcr
                .write_with_zero(|w| w.rxtdis().set_bit().txtdis().set_bit());
        }

        // Setup prescalar and startup time
        let prescaler = (clock.frequency() / (2 * 20_u32.MHz::<1, 1>()) - 1) as u8;
        adc.mr
            .modify(|_, w| unsafe { w.prescal().bits(prescaler).startup().sut512() });

        /* Set ADC timing.
         * Formula:
         *
         *     Ttrack minimum = 0.054 * Zsource + 205
         *     Ttrack minimum = 0.054 * 1.5k + 205 = 286 ns
         *     Ttrack minimum = 0.054 * 10k + 205 = 745 ns
         *     Ttrack minimum = 0.054 * 20k + 205 = 1285 ns
         *     20MHz -> 50 ns * 15 cycles = 750 ns
         *     750 ns > 286 ns -> Tracktim can be set to 0
         *     750 ns > 745 ns -> Tracktim can be set to 0
         *     750 ns < 1285 ns -> Tracktim can be set to 10 => 750 ns + 550 ns (10) = 1300 ns
         *     See sam4s datasheet Figure 44-21 and Table 44-41 for details
         *
         *     Transfer Time = (TRANSFER * 2 + 3) / ADCClock
         *     Tracking Time = (TRACKTIM + 1) / ADCClock
         *     Settling Time = settling value / ADCClock
         *
         *     Hold Time
         *     (datasheet recommends (2) or 350 ns in this case)
         *     Transfer Time = (0 * 2 + 3) / 20MHz = 150 ns
         *     Transfer Time = (1 * 2 + 3) / 20MHz = 250 ns
         *     Transfer Time = (2 * 2 + 3) / 20MHz = 350 ns
         *     Transfer Time = (3 * 2 + 3) / 20MHz = 450 ns
         *
         *     Track Time
         *     Tracking Time = (0 + 1) / 20MHz = 50 ns
         *     Tracking Time = (1 + 1) / 20MHz = 100 ns
         *     Tracking Time = (2 + 1) / 20MHz = 150 ns
         *     Tracking Time = (3 + 1) / 20MHz = 200 ns
         *     Tracking Time = (4 + 1) / 20MHz = 250 ns
         *     Tracking Time = (5 + 1) / 20MHz = 300 ns
         *     Tracking Time = (6 + 1) / 20MHz = 350 ns
         *     Tracking Time = (7 + 1) / 20MHz = 400 ns
         *     Tracking Time = (8 + 1) / 20MHz = 450 ns
         *     Tracking Time = (9 + 1) / 20MHz = 500 ns
         *     Tracking Time = (10 + 1) / 20MHz = 550 ns
         *     Tracking Time = (11 + 1) / 20MHz = 600 ns
         *     Tracking Time = (12 + 1) / 20MHz = 650 ns
         *     Tracking Time = (13 + 1) / 20MHz = 700 ns
         *     Tracking Time = (14 + 1) / 20MHz = 750 ns
         *     Tracking Time = (15 + 1) / 20MHz = 800 ns
         *
         *     Analog Settling Time
         *     (Most examples seem to use (3) or 850 ns in this case)
         *     Settling Time = 3 / 20MHz = 150 ns (0)
         *     Settling Time = 5 / 20MHz = 250 ns (1)
         *     Settling Time = 9 / 20MHz = 450 ns (2)
         *     Settling Time = 17 / 20MHz = 850 ns (3)
         *
         * const uint8_t tracking_time = 15;
         * const uint8_t transfer_period = 2; // Recommended to be set to 2 by datasheet (42.7.2)
         * adc_configure_timing(ADC, tracking_time, ADC_SETTLING_TIME_2, transfer_period);
         */
        let tracking_time = 10;
        let transfer_period = 2;
        adc.mr.modify(|_, w| unsafe {
            w.transfer()
                .bits(transfer_period)
                .tracktim()
                .bits(tracking_time)
                .settling()
                .ast17()
        });

        // Enable temperature sensor
        adc.acr.modify(|_, w| w.tson().set_bit());

        // Allow different gain/offset values for each channel
        adc.mr.modify(|_, w| w.anach().allowed());

        Self {
            adc,
            clock: PhantomData,
        }
    }

    /// Startup time
    /// See
    /// <https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11100-32-bit%20Cortex-M4-Microcontroller-SAM4S_Datasheet.pdf>
    /// page 1088
    pub fn startup_time(&mut self, sut: StartupTime) {
        self.adc.mr.modify(|_, w| match sut {
            StartupTime::Sut0 => w.startup().sut0(),
            StartupTime::Sut8 => w.startup().sut8(),
            StartupTime::Sut16 => w.startup().sut16(),
            StartupTime::Sut24 => w.startup().sut24(),
            StartupTime::Sut64 => w.startup().sut64(),
            StartupTime::Sut80 => w.startup().sut80(),
            StartupTime::Sut96 => w.startup().sut96(),
            StartupTime::Sut112 => w.startup().sut112(),
            StartupTime::Sut512 => w.startup().sut512(),
            StartupTime::Sut576 => w.startup().sut576(),
            StartupTime::Sut640 => w.startup().sut640(),
            StartupTime::Sut704 => w.startup().sut704(),
            StartupTime::Sut768 => w.startup().sut768(),
            StartupTime::Sut832 => w.startup().sut832(),
            StartupTime::Sut896 => w.startup().sut896(),
            StartupTime::Sut960 => w.startup().sut960(),
        });
    }

    /// Tracking time
    /// Tracking Time = (TRACKTIM + 1) * ADCCLK period
    /// See
    /// <https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11100-32-bit%20Cortex-M4-Microcontroller-SAM4S_Datasheet.pdf>
    /// page 1088
    pub fn tracking_time(&mut self, tracking_time: TrackingTime) {
        self.adc
            .mr
            .modify(|_, w| unsafe { w.tracktim().bits(tracking_time as u8) });
    }

    /// Transfer time / hold time
    /// Tranfser time = (TRANSFER * 2 + 3) * ADCCLK period
    /// See
    /// <https://ww1.microchip.com/downloads/en/Appnotes/Atmel-42298-SAM3-4S-4C-Analog-to-digital-Converter-ADC_ApplicationNote_AT06860.pdf>
    /// page 28
    /// Datasheet recommends this is set to at least 2 (Tt7)
    /// See
    /// <https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11100-32-bit%20Cortex-M4-Microcontroller-SAM4S_Datasheet.pdf>
    /// page 1088
    pub fn transfer_time(&mut self, transfer_time: TransferTime) {
        self.adc
            .mr
            .modify(|_, w| unsafe { w.transfer().bits(transfer_time as u8) });
    }

    /// Settling time
    /// (most example code seems to use 3 (17 periods of ADCCLK))
    pub fn settling_time(&mut self, ast: SettlingTime) {
        self.adc.mr.modify(|_, w| match ast {
            SettlingTime::Ast3 => w.settling().ast3(),
            SettlingTime::Ast5 => w.settling().ast5(),
            SettlingTime::Ast9 => w.settling().ast9(),
            SettlingTime::Ast17 => w.settling().ast17(),
        });
    }

    /// Prescaler
    /// prescaler = f_peripheral_clk / (2 x f_adcclk)) - 1
    /// Recommended to be set to 20 MHz (unless you are having issues)
    pub fn prescaler(&mut self, prescaler: u8) {
        self.adc
            .mr
            .modify(|_, w| unsafe { w.prescal().bits(prescaler) });
    }

    /// Enables channel number tags
    /// Can be used for DMA to tag channel data.
    /// Not necessary, as by default the ordering is by the enabled channels
    /// or per the set sequence. Mainly for convenience.
    pub fn enable_tags(&mut self) {
        // Enable channel number tag for LCDR
        self.adc.emr.modify(|_, w| w.tag().set_bit());
    }

    /// Disables channel number tags
    pub fn disable_tags(&mut self) {
        // Enable channel number tag for LCDR
        self.adc.emr.modify(|_, w| w.tag().clear_bit());
    }

    /// Reterns a PIN-like reference for the temperature sensor
    /// Used to enabled and start sampling of the temperature channel (15)
    /// Cannot use pins as there is no pin reference.
    /// ```
    /// let mut adc = Adc::new(
    ///     peripherals.ADC,
    ///     clocks.peripheral_clocks.adc.into_enabled_clock(),
    /// );
    /// let temp_sensor = adc.temp_sensor();
    /// adc.enable_channel(temp_sensor);
    /// ```
    pub fn temp_sensor(&mut self) -> &'static mut TempSensor {
        singleton!(: TempSensor = TempSensor {}).unwrap()
    }

    /// Sets the channel read sequence
    /// Used with the PDC
    /// NOTE: This sequence is a bit odd, the sequence has up to 15 channels.
    ///       A channel register is ONLY used if the corresponding ADC channel is also enabled.
    ///       i.e. if you want [0, 1, 2, 3] you need to enable channels 0, 1, 2, 3 even if you
    ///       are not reading from those ADC channels.
    ///       If you want to read from [10, 14, 15] but want to read in the order
    ///       [10, 10, 14, 15, 15], you must enable 2 additional channels and use those channels in
    ///       the sequence. For example enable channels 0, 1, 10, 14, 15 and use the sequence
    ///       [10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 15, 15] where the 0's are ignored.
    pub fn sequence(&mut self, channels: &[u8]) {
        for (pos, ch) in channels.iter().enumerate() {
            defmt::trace!("Setting channel {} to {}", pos, *ch);
            match pos {
                0 => self.adc.seqr1.modify(|_, w| unsafe { w.usch1().bits(*ch) }),
                1 => self.adc.seqr1.modify(|_, w| unsafe { w.usch2().bits(*ch) }),
                2 => self.adc.seqr1.modify(|_, w| unsafe { w.usch3().bits(*ch) }),
                3 => self.adc.seqr1.modify(|_, w| unsafe { w.usch4().bits(*ch) }),
                4 => self.adc.seqr1.modify(|_, w| unsafe { w.usch5().bits(*ch) }),
                5 => self.adc.seqr1.modify(|_, w| unsafe { w.usch6().bits(*ch) }),
                6 => self.adc.seqr1.modify(|_, w| unsafe { w.usch7().bits(*ch) }),
                7 => self.adc.seqr1.modify(|_, w| unsafe { w.usch8().bits(*ch) }),
                8 => self.adc.seqr2.modify(|_, w| unsafe { w.usch9().bits(*ch) }),
                9 => self
                    .adc
                    .seqr2
                    .modify(|_, w| unsafe { w.usch10().bits(*ch) }),
                10 => self
                    .adc
                    .seqr2
                    .modify(|_, w| unsafe { w.usch11().bits(*ch) }),
                11 => self
                    .adc
                    .seqr2
                    .modify(|_, w| unsafe { w.usch12().bits(*ch) }),
                12 => self
                    .adc
                    .seqr2
                    .modify(|_, w| unsafe { w.usch13().bits(*ch) }),
                13 => self
                    .adc
                    .seqr2
                    .modify(|_, w| unsafe { w.usch14().bits(*ch) }),
                14 => self
                    .adc
                    .seqr2
                    .modify(|_, w| unsafe { w.usch15().bits(*ch) }),
                _ => {
                    panic!("Invalid sequence position: {}", pos);
                }
            }
        }
    }

    /// Enable ADC sequencing
    /// When enabled, the ADC channel sequence register is used to determine the ADC read order
    pub fn enable_sequencing(&mut self) {
        self.adc.mr.modify(|_, w| w.useq().set_bit());
    }

    /// Disable ADC sequencing
    /// When disabled (default), the ADC channels are converted by (numerical) channel order
    pub fn disable_sequencing(&mut self) {
        self.adc.mr.modify(|_, w| w.useq().clear_bit());
    }

    /// Set the powersaving mode
    /// By default set to Normal (no powersaving)
    pub fn powersaving(&mut self, ps: Powersaving) {
        match ps {
            Powersaving::Normal => self.adc.mr.modify(|_, w| w.sleep().normal()),
            Powersaving::FastWakeup => self.adc.mr.modify(|_, w| w.sleep().sleep().fwup().on()),
            Powersaving::Sleep => self.adc.mr.modify(|_, w| w.sleep().sleep().fwup().off()),
        }
    }

    /// Set channel single-ended gain
    /// See Section 42.6.10 in ATSAM4S datasheet for details
    /// NOTE: You must run calibration if gain settings are changed
    pub fn gain<PIN: Channel<ADC, ID = u8>>(&mut self, _pin: &mut PIN, gain: SingleEndedGain) {
        match PIN::channel() {
            0 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain0().bits(gain as u8) }),
            1 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain1().bits(gain as u8) }),
            2 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain2().bits(gain as u8) }),
            3 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain3().bits(gain as u8) }),
            4 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain4().bits(gain as u8) }),
            5 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain5().bits(gain as u8) }),
            6 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain6().bits(gain as u8) }),
            7 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain7().bits(gain as u8) }),
            8 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain8().bits(gain as u8) }),
            9 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain9().bits(gain as u8) }),
            10 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain10().bits(gain as u8) }),
            11 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain11().bits(gain as u8) }),
            12 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain12().bits(gain as u8) }),
            13 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain13().bits(gain as u8) }),
            14 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain14().bits(gain as u8) }),
            15 => self
                .adc
                .cgr
                .modify(|_, w| unsafe { w.gain15().bits(gain as u8) }),
            _ => {
                panic!("Invalid channel: {}", PIN::channel());
            }
        }
    }

    /// Set voltage offset
    /// See Section 42.6.10 in ATSAM4S datasheet for details
    /// NOTE: You must run calibration if offset settings are changed
    pub fn offset<PIN: Channel<ADC, ID = u8>>(&mut self, _pin: &mut PIN, offset: bool) {
        match PIN::channel() {
            0 => self.adc.cor.modify(|_, w| w.off0().bit(offset)),
            1 => self.adc.cor.modify(|_, w| w.off1().bit(offset)),
            2 => self.adc.cor.modify(|_, w| w.off2().bit(offset)),
            3 => self.adc.cor.modify(|_, w| w.off3().bit(offset)),
            4 => self.adc.cor.modify(|_, w| w.off4().bit(offset)),
            5 => self.adc.cor.modify(|_, w| w.off5().bit(offset)),
            6 => self.adc.cor.modify(|_, w| w.off6().bit(offset)),
            7 => self.adc.cor.modify(|_, w| w.off7().bit(offset)),
            8 => self.adc.cor.modify(|_, w| w.off8().bit(offset)),
            9 => self.adc.cor.modify(|_, w| w.off9().bit(offset)),
            10 => self.adc.cor.modify(|_, w| w.off10().bit(offset)),
            11 => self.adc.cor.modify(|_, w| w.off11().bit(offset)),
            12 => self.adc.cor.modify(|_, w| w.off12().bit(offset)),
            13 => self.adc.cor.modify(|_, w| w.off13().bit(offset)),
            14 => self.adc.cor.modify(|_, w| w.off14().bit(offset)),
            15 => self.adc.cor.modify(|_, w| w.off15().bit(offset)),
            _ => {
                panic!("Invalid channel: {}", PIN::channel());
            }
        }
    }

    /// Autocalibration
    /// Wait will block until autocalibration is complete
    pub fn autocalibration(&mut self, wait: bool) {
        unsafe { self.adc.cr.write_with_zero(|w| w.autocal().set_bit()) };

        if wait {
            while !self.calibration_ready() {}
            defmt::trace!("Calibration complete");
        }
    }

    /// Checks if calibration is ready
    /// Will return false if calibration is not ready, or calibration has not been requested
    pub fn calibration_ready(&self) -> bool {
        self.adc.isr.read().eocal().bit()
    }

    fn enable_freerunning(&mut self) {
        self.adc.mr.modify(|_, w| w.freerun().on());
    }

    fn disable_freerunning(&mut self) {
        self.adc.mr.modify(|_, w| w.freerun().off());
    }

    fn synchronous_convert<PIN: Channel<ADC, ID = u8>>(&mut self, _pin: &mut PIN) -> u16 {
        self.start_conversion();
        // Poll End-of-Conversions status bit
        while !match PIN::channel() {
            0 => self.adc.isr.read().eoc0().bit(),
            1 => self.adc.isr.read().eoc1().bit(),
            2 => self.adc.isr.read().eoc2().bit(),
            3 => self.adc.isr.read().eoc3().bit(),
            4 => self.adc.isr.read().eoc4().bit(),
            5 => self.adc.isr.read().eoc5().bit(),
            6 => self.adc.isr.read().eoc6().bit(),
            7 => self.adc.isr.read().eoc7().bit(),
            8 => self.adc.isr.read().eoc8().bit(),
            9 => self.adc.isr.read().eoc9().bit(),
            10 => self.adc.isr.read().eoc10().bit(),
            11 => self.adc.isr.read().eoc11().bit(),
            12 => self.adc.isr.read().eoc12().bit(),
            13 => self.adc.isr.read().eoc13().bit(),
            14 => self.adc.isr.read().eoc14().bit(),
            15 => self.adc.isr.read().eoc15().bit(),
            _ => {
                panic!("Invalid channel: {}", PIN::channel());
            }
        } {}
        // Read data register for the specified channel
        self.adc.cdr[PIN::channel() as usize].read().data().bits()
    }

    fn start_conversion(&mut self) {
        unsafe { self.adc.cr.write_with_zero(|w| w.start().set_bit()) };
    }

    /// Enables the ADC pin channel
    /// A channel, if used, must be enabled before autocalibration
    /// This is needed to determine the various gain+offset settings used
    /// See Section in 42.6.12 in the ATSAM4S datasheet for more details
    pub fn enable_channel<PIN: Channel<ADC, ID = u8>>(&mut self, _pin: &mut PIN) {
        self.enable_channel_id(PIN::channel());
    }

    /// Useful when you need to access a bit for an internal pin that's not exposed
    /// as part of your chip's pinout
    pub fn enable_channel_id(&mut self, channel: u8) {
        unsafe {
            match channel {
                0 => self.adc.cher.write_with_zero(|w| w.ch0().set_bit()),
                1 => self.adc.cher.write_with_zero(|w| w.ch1().set_bit()),
                2 => self.adc.cher.write_with_zero(|w| w.ch2().set_bit()),
                3 => self.adc.cher.write_with_zero(|w| w.ch3().set_bit()),
                4 => self.adc.cher.write_with_zero(|w| w.ch4().set_bit()),
                5 => self.adc.cher.write_with_zero(|w| w.ch5().set_bit()),
                6 => self.adc.cher.write_with_zero(|w| w.ch6().set_bit()),
                7 => self.adc.cher.write_with_zero(|w| w.ch7().set_bit()),
                8 => self.adc.cher.write_with_zero(|w| w.ch8().set_bit()),
                9 => self.adc.cher.write_with_zero(|w| w.ch9().set_bit()),
                10 => self.adc.cher.write_with_zero(|w| w.ch10().set_bit()),
                11 => self.adc.cher.write_with_zero(|w| w.ch11().set_bit()),
                12 => self.adc.cher.write_with_zero(|w| w.ch12().set_bit()),
                13 => self.adc.cher.write_with_zero(|w| w.ch13().set_bit()),
                14 => self.adc.cher.write_with_zero(|w| w.ch14().set_bit()),
                15 => self.adc.cher.write_with_zero(|w| w.ch15().set_bit()),
                _ => {
                    panic!("Invalid channel: {}", channel);
                }
            }
        }
    }

    pub fn disable_channel<PIN: Channel<ADC, ID = u8>>(&mut self, _pin: &mut PIN) {
        self.disable_channel_id(PIN::channel());
    }

    pub fn disable_channel_id(&mut self, channel: u8) {
        unsafe {
            match channel {
                0 => self.adc.chdr.write_with_zero(|w| w.ch0().set_bit()),
                1 => self.adc.chdr.write_with_zero(|w| w.ch1().set_bit()),
                2 => self.adc.chdr.write_with_zero(|w| w.ch2().set_bit()),
                3 => self.adc.chdr.write_with_zero(|w| w.ch3().set_bit()),
                4 => self.adc.chdr.write_with_zero(|w| w.ch4().set_bit()),
                5 => self.adc.chdr.write_with_zero(|w| w.ch5().set_bit()),
                6 => self.adc.chdr.write_with_zero(|w| w.ch6().set_bit()),
                7 => self.adc.chdr.write_with_zero(|w| w.ch7().set_bit()),
                8 => self.adc.chdr.write_with_zero(|w| w.ch8().set_bit()),
                9 => self.adc.chdr.write_with_zero(|w| w.ch9().set_bit()),
                10 => self.adc.chdr.write_with_zero(|w| w.ch10().set_bit()),
                11 => self.adc.chdr.write_with_zero(|w| w.ch11().set_bit()),
                12 => self.adc.chdr.write_with_zero(|w| w.ch12().set_bit()),
                13 => self.adc.chdr.write_with_zero(|w| w.ch13().set_bit()),
                14 => self.adc.chdr.write_with_zero(|w| w.ch14().set_bit()),
                15 => self.adc.chdr.write_with_zero(|w| w.ch15().set_bit()),
                _ => {
                    panic!("Invalid channel: {}", channel);
                }
            }
        }
    }

    /// Enables interrupts each channel
    /// This does not use DRDY as DRDY under freerunning mode using interrupts
    /// has the tendency to lose samples. Instead each channel interrupt is used instead
    /// so that no samples are lost.
    fn enable_interrupts<PIN: Channel<ADC, ID = u8>>(&mut self, _pin: &mut PIN) {
        unsafe {
            match PIN::channel() {
                0 => self.adc.ier.write_with_zero(|w| w.eoc0().set_bit()),
                1 => self.adc.ier.write_with_zero(|w| w.eoc1().set_bit()),
                2 => self.adc.ier.write_with_zero(|w| w.eoc2().set_bit()),
                3 => self.adc.ier.write_with_zero(|w| w.eoc3().set_bit()),
                4 => self.adc.ier.write_with_zero(|w| w.eoc4().set_bit()),
                5 => self.adc.ier.write_with_zero(|w| w.eoc5().set_bit()),
                6 => self.adc.ier.write_with_zero(|w| w.eoc6().set_bit()),
                7 => self.adc.ier.write_with_zero(|w| w.eoc7().set_bit()),
                8 => self.adc.ier.write_with_zero(|w| w.eoc8().set_bit()),
                9 => self.adc.ier.write_with_zero(|w| w.eoc9().set_bit()),
                10 => self.adc.ier.write_with_zero(|w| w.eoc10().set_bit()),
                11 => self.adc.ier.write_with_zero(|w| w.eoc11().set_bit()),
                12 => self.adc.ier.write_with_zero(|w| w.eoc12().set_bit()),
                13 => self.adc.ier.write_with_zero(|w| w.eoc13().set_bit()),
                14 => self.adc.ier.write_with_zero(|w| w.eoc14().set_bit()),
                15 => self.adc.ier.write_with_zero(|w| w.eoc15().set_bit()),
                _ => {
                    panic!("Invalid channel: {}", PIN::channel());
                }
            }
        }
    }

    /// Disables the interrupts.
    fn disable_interrupts<PIN: Channel<ADC, ID = u8>>(&mut self, _pin: &mut PIN) {
        unsafe {
            match PIN::channel() {
                0 => self.adc.idr.write_with_zero(|w| w.eoc0().set_bit()),
                1 => self.adc.idr.write_with_zero(|w| w.eoc1().set_bit()),
                2 => self.adc.idr.write_with_zero(|w| w.eoc2().set_bit()),
                3 => self.adc.idr.write_with_zero(|w| w.eoc3().set_bit()),
                4 => self.adc.idr.write_with_zero(|w| w.eoc4().set_bit()),
                5 => self.adc.idr.write_with_zero(|w| w.eoc5().set_bit()),
                6 => self.adc.idr.write_with_zero(|w| w.eoc6().set_bit()),
                7 => self.adc.idr.write_with_zero(|w| w.eoc7().set_bit()),
                8 => self.adc.idr.write_with_zero(|w| w.eoc8().set_bit()),
                9 => self.adc.idr.write_with_zero(|w| w.eoc9().set_bit()),
                10 => self.adc.idr.write_with_zero(|w| w.eoc10().set_bit()),
                11 => self.adc.idr.write_with_zero(|w| w.eoc11().set_bit()),
                12 => self.adc.idr.write_with_zero(|w| w.eoc12().set_bit()),
                13 => self.adc.idr.write_with_zero(|w| w.eoc13().set_bit()),
                14 => self.adc.idr.write_with_zero(|w| w.eoc14().set_bit()),
                15 => self.adc.idr.write_with_zero(|w| w.eoc15().set_bit()),
                _ => {
                    panic!("Invalid channel: {}", PIN::channel());
                }
            }
        }
    }

    /// Checks for a ready value on the specified pin
    fn service_interrupt_ready<PIN: Channel<ADC, ID = u8>>(
        &mut self,
        _pin: &mut PIN,
    ) -> Option<u16> {
        // If interrupt is not enable for this channel, don't bother checking
        if !match PIN::channel() {
            0 => self.adc.imr.read().eoc0().bit(),
            1 => self.adc.imr.read().eoc1().bit(),
            2 => self.adc.imr.read().eoc2().bit(),
            3 => self.adc.imr.read().eoc3().bit(),
            4 => self.adc.imr.read().eoc4().bit(),
            5 => self.adc.imr.read().eoc5().bit(),
            6 => self.adc.imr.read().eoc6().bit(),
            7 => self.adc.imr.read().eoc7().bit(),
            8 => self.adc.imr.read().eoc8().bit(),
            9 => self.adc.imr.read().eoc9().bit(),
            10 => self.adc.imr.read().eoc10().bit(),
            11 => self.adc.imr.read().eoc11().bit(),
            12 => self.adc.imr.read().eoc12().bit(),
            13 => self.adc.imr.read().eoc13().bit(),
            14 => self.adc.imr.read().eoc14().bit(),
            15 => self.adc.imr.read().eoc15().bit(),
            _ => {
                panic!("Invalid channel: {}", PIN::channel());
            }
        } {
            return None;
        }

        // Check to see if the channel is ready before reading
        if match PIN::channel() {
            0 => self.adc.isr.read().eoc0().bit(),
            1 => self.adc.isr.read().eoc1().bit(),
            2 => self.adc.isr.read().eoc2().bit(),
            3 => self.adc.isr.read().eoc3().bit(),
            4 => self.adc.isr.read().eoc4().bit(),
            5 => self.adc.isr.read().eoc5().bit(),
            6 => self.adc.isr.read().eoc6().bit(),
            7 => self.adc.isr.read().eoc7().bit(),
            8 => self.adc.isr.read().eoc8().bit(),
            9 => self.adc.isr.read().eoc9().bit(),
            10 => self.adc.isr.read().eoc10().bit(),
            11 => self.adc.isr.read().eoc11().bit(),
            12 => self.adc.isr.read().eoc12().bit(),
            13 => self.adc.isr.read().eoc13().bit(),
            14 => self.adc.isr.read().eoc14().bit(),
            15 => self.adc.isr.read().eoc15().bit(),
            _ => {
                panic!("Invalid channel: {}", PIN::channel());
            }
        } {
            Some(self.adc.cdr[PIN::channel() as usize].read().data().bits())
        } else {
            None
        }
    }
}

impl ConversionMode for SingleConversion {
    fn on_start(_adc: &mut Adc) {}

    fn on_complete<PIN: Channel<ADC, ID = u8>>(adc: &mut Adc, pin: &mut PIN) {
        adc.disable_interrupts(pin);
    }

    fn on_stop<PIN: Channel<ADC, ID = u8>>(_adc: &mut Adc, _pin: &mut PIN) {}
}

impl ConversionMode for FreeRunning {
    fn on_start(adc: &mut Adc) {
        adc.enable_freerunning();
    }

    fn on_complete<PIN: Channel<ADC, ID = u8>>(_adc: &mut Adc, _pin: &mut PIN) {}

    fn on_stop<PIN: Channel<ADC, ID = u8>>(adc: &mut Adc, pin: &mut PIN) {
        adc.disable_interrupts(pin);
        adc.disable_freerunning();
    }
}

impl<C> InterruptAdc<C>
where
    C: ConversionMode,
{
    pub fn service_interrupt_ready<PIN: Channel<ADC, ID = u8>>(
        &mut self,
        pin: &mut PIN,
    ) -> Option<u16> {
        if let Some(res) = self.adc.service_interrupt_ready(pin) {
            C::on_complete(&mut self.adc, pin);
            Some(res)
        } else {
            None
        }
    }

    /// Starts conversion sampling on specified pin
    /// NOTE: You must enable the channel first before starting the conversion
    ///       If you do not start the conversion on pins that have been enabled
    ///       those pins will read ADC values but will not trigger an interrupt.
    pub fn start_conversion<PIN: Channel<ADC, ID = u8>>(&mut self, pin: &mut PIN) {
        C::on_start(&mut self.adc);
        self.adc.enable_interrupts(pin);
        self.adc.start_conversion();
    }

    pub fn stop_conversion<PIN: Channel<ADC, ID = u8>>(&mut self, pin: &mut PIN) {
        C::on_stop(&mut self.adc, pin);
    }

    /// Reverts the InterruptAdc back to Adc
    pub fn revert(self) -> Adc {
        self.adc
    }
}

impl<C> From<Adc> for InterruptAdc<C>
where
    C: ConversionMode,
{
    fn from(adc: Adc) -> Self {
        Self {
            adc,
            m: PhantomData {},
        }
    }
}

impl<WORD, PIN> OneShot<ADC, WORD, PIN> for Adc
where
    WORD: From<u16>,
    PIN: Channel<ADC, ID = u8>,
{
    type Error = ();

    fn read(&mut self, pin: &mut PIN) -> nb::Result<WORD, Self::Error> {
        // Trigger single shot
        let result = self.synchronous_convert(pin);
        Ok(result.into())
    }
}

macro_rules! adc_pins {
    (
        $(
            $PinId:ident: ($CHAN:literal),
        )+
    ) => {
        $(
            impl Channel<ADC> for $PinId<ExFn> {
               type ID = u8;
               fn channel() -> Self::ID { $CHAN }
            }
        )+
    }
}

/// Identifies the ADC channel number for a given pin
/// This is inconvenient to do directly as you want to abstract away the explicit pin type
/// TODO: Ideally this should be a const fn, but we'll have to wait for that to be stabilized
///       <https://github.com/rust-lang/rust/issues/67792>
pub fn ch<PIN: Channel<ADC, ID = u8>>(_pin: &PIN) -> u8 {
    PIN::channel()
}

#[cfg(feature = "atsam4s")]
adc_pins! {
    Pa17: (0),
    Pa18: (1),
    Pa19: (2),
    Pa20: (3),
    Pb0: (4),
    Pb1: (5),
    Pb2: (6),
    Pb3: (7),
}

#[cfg(any(feature = "atsam4s_b", feature = "atsam4s_c"))]
adc_pins! {
    Pa21: (8),
    Pa22: (9),
}

#[cfg(feature = "atsam4s_c")]
adc_pins! {
    Pc13: (10),
    Pc15: (11),
    Pc12: (12),
    Pc29: (13),
    Pc30: (14),
}

/// Channel 15 is reserved for the temperature sensor
#[cfg(feature = "atsam4s")]
pub struct TempSensor {}

#[cfg(feature = "atsam4s")]
impl Channel<ADC> for TempSensor {
    type ID = u8;
    fn channel() -> u8 {
        15
    }
}

// Setup PDC Rx functionality
pdc_rx! { Adc: adc, isr }

impl Adc {
    /// Configures the ADC with PDC in single sequence mode
    /// This will take a single sample of all the enable channels.
    /// If sequence() has been set, then only the channels in the sequence will
    /// be read.
    ///
    /// Since this is a single capture, the buffer used must be equal to the number
    /// of channels going to be read (a smaller buffer would also work, but doesn't really
    /// make sense). If the buffer is too large, the DMA transfer will not complete
    /// and wait for the next ADC conversion event.
    ///
    /// Polling example
    /// ```
    /// let mut adc = Adc::new(
    ///     cx.device.ADC,
    ///     clocks.peripheral_clocks.adc.into_enabled_clock(),
    /// );
    ///
    /// // Enable 3 channels
    /// adc.enable_channel(&mut pins.sense1);
    /// adc.enable_channel(&mut pins.sense2);
    /// adc.enable_channel(&mut pins.sense3);
    ///
    /// // Enable DMA mode
    /// let adc = adc.with_pdc();
    ///
    /// // Note that the buffer size is 3 and 3 channels were enabled
    /// let buf = singleton!(: [u16; 4] = [0; 4]).unwrap();
    ///
    /// // Read and wait for the result
    /// let (buf, adc) = adc.read(buf).wait();
    /// defmt::trace!("DMA BUF: {}", buf);
    ///
    /// // Revert AdcDma<SingleSequence> back to Adc
    /// let adc = adc.revert();
    /// ```
    ///
    /// Interrupt example (RTIC)
    /// ```
    /// #[local]
    /// struct Local {
    ///     adc: Option<Transfer<W, &'static mut [u16; 6], RxDma<AdcPayload<SingleSequence>>>>,
    /// }
    ///
    /// #[init(local = [adc_buf: [u16; 3] = [0; 3]])]
    /// fn init(mut cx: init::Context) -> (Shared, Local, init::Monotonics) {
    ///     let mut adc = Adc::new(
    ///         cx.device.ADC,
    ///         clocks.peripheral_clocks.adc.into_enabled_clock(),
    ///     );
    ///
    ///     // Enable 3 channels
    ///     adc.enable_channel(&mut pins.sense1);
    ///     adc.enable_channel(&mut pins.sense2);
    ///     adc.enable_channel(&mut pins.sense3);
    ///
    ///     // Enable DMA mode
    ///     let adc = adc.with_pdc();
    ///     (
    ///         Shared {},
    ///         Local {
    ///             adc: Some(adc.read(cx.local.adc_buf)),
    ///         },
    ///         init::Monotonics {},
    ///     )
    /// }
    ///
    /// #[task(binds = ADC, local = [adc])]
    /// fn adc(cx: adc::Context) {
    ///     let (buf, adc) = cx.local.adc.take().unwrap().wait();
    ///     defmt::trace!("DMA BUF: {}", buf);
    ///     cx.local.adc.replace(adc.read(buf));
    /// }
    /// ```
    pub fn with_pdc(self) -> AdcDma<SingleSequence> {
        let payload = AdcPayload {
            adc: self,
            _mode: PhantomData,
        };
        RxDma { payload }
    }

    /// Configures the ADC with PDC in single sequence mode
    /// This will take a single sample of all the enable channels.
    /// If sequence() has been set, then only the channels in the sequence will
    /// be read.
    ///
    /// Since this is a continous capture (e.g. freerunning), the buffer size may be any
    /// size and the DMA transfer will complete once the buffer is full.
    /// It is recommended to make the buffer a multiple of the number of channels enabled
    /// (or number of channels used in the sequence).
    ///
    /// Polling example
    /// ```
    /// let mut adc = Adc::new(
    ///     cx.device.ADC,
    ///     clocks.peripheral_clocks.adc.into_enabled_clock(),
    /// );
    ///
    /// // Enable 3 channels
    /// adc.enable_channel(&mut pins.sense1);
    /// adc.enable_channel(&mut pins.sense2);
    /// adc.enable_channel(&mut pins.sense3);
    ///
    /// // Reorder sequence (by default, the channel numbers dictate the order)
    /// adc.sequence(&mut [2, 1, 0]);
    /// adc.enable_sequencing();
    ///
    /// // Enable DMA mode
    /// let adc = adc.with_continuous_pdc();
    ///
    /// // Note that the buffer size is 6 and 3 channels were enabled
    /// // Since we're running in freerunning mode the entire will fill up before
    /// // the PDC notes completion.
    /// let buf = singleton!(: [u16; 6] = [0; 6]).unwrap();
    ///
    /// // Read and wait for the result
    /// let (buf, adc) = adc.read(buf).wait();
    /// defmt::trace!("DMA BUF: {}", buf);
    ///
    /// // Revert AdcDma<Continuous> back to Adc
    /// let adc = adc.revert();
    /// ```
    ///
    /// Interrupt example (RTIC)
    /// ```
    /// #[local]
    /// struct Local {
    ///     adc: Option<Transfer<W, &'static mut [u16; 6], RxDma<AdcPayload<Continuous>>>>,
    /// }
    ///
    /// #[init(local = [adc_buf: [u16; 6] = [0; 6]])]
    /// fn init(mut cx: init::Context) -> (Shared, Local, init::Monotonics) {
    ///     let mut adc = Adc::new(
    ///         cx.device.ADC,
    ///         clocks.peripheral_clocks.adc.into_enabled_clock(),
    ///     );
    ///
    ///     // Enable 3 channels
    ///     adc.enable_channel(&mut pins.sense1);
    ///     adc.enable_channel(&mut pins.sense2);
    ///     adc.enable_channel(&mut pins.sense3);
    ///
    ///     // Reorder sequence (by default, the channel numbers dictate the order)
    ///     adc.sequence(&mut [2, 1, 0]);
    ///     adc.enable_sequencing();
    ///
    ///     // Enable DMA mode
    ///     let adc = adc.with_continuous_pdc();
    ///     (
    ///         Shared {},
    ///         Local {
    ///             adc: Some(adc.read(cx.local.adc_buf)),
    ///         },
    ///         init::Monotonics {},
    ///     )
    /// }
    ///
    /// #[task(binds = ADC, local = [adc])]
    /// fn adc(cx: adc::Context) {
    ///     let (buf, adc) = cx.local.adc.take().unwrap().wait();
    ///     defmt::trace!("DMA BUF: {}", buf);
    ///     cx.local.adc.replace(adc.read(buf));
    /// }
    /// ```
    pub fn with_continuous_pdc(self) -> AdcDma<Continuous> {
        let payload = AdcPayload {
            adc: self,
            _mode: PhantomData,
        };
        RxDma { payload }
    }
}

/// Continuous mode
pub struct Continuous;
/// SingleSequence mode
pub struct SingleSequence;

pub struct AdcPayload<MODE> {
    adc: Adc,
    _mode: PhantomData<MODE>,
}

pub type AdcDma<MODE> = RxDma<AdcPayload<MODE>>;

impl<MODE> AdcDma<MODE>
where
    Self: TransferPayload,
{
    /// Reverts the AdcDma back to Adc
    pub fn revert(mut self) -> Adc {
        // Disable PDC in case it is still enabled
        self.payload.adc.stop_rx_pdc();

        self.payload.adc
    }
}

impl<MODE> Receive for AdcDma<MODE> {
    type TransmittedWord = u16;
}

impl<B, MODE> ReadDma<B, u16> for AdcDma<MODE>
where
    Self: TransferPayload,
    B: WriteBuffer<Word = u16>,
{
    /// Assigns the buffer, enables PDC and starts ADC conversion
    fn read(mut self, mut buffer: B) -> Transfer<W, B, Self> {
        // NOTE(unsafe) We own the buffer now and we won't call other `&mut` on it
        // until the end of the transfer.
        let (ptr, len) = unsafe { buffer.write_buffer() };
        self.payload.adc.set_receive_address(ptr as u32);
        self.payload.adc.set_receive_counter(len as u16);

        compiler_fence(Ordering::Release);
        self.start();

        Transfer::w(buffer, self)
    }
}

impl<B, MODE> ReadDmaPaused<B, u16> for AdcDma<MODE>
where
    Self: TransferPayload,
    B: WriteBuffer<Word = u16>,
{
    /// Assigns the buffer, prepares PDC but does not enable the PDC
    /// Useful when there is strict timing on when the ADC conversion should start
    ///
    /// transfer.resume() can be used to start the transfer
    fn read_paused(mut self, mut buffer: B) -> Transfer<W, B, Self> {
        // NOTE(unsafe) We own the buffer now and we won't call other `&mut` on it
        // until the end of the transfer.
        let (ptr, len) = unsafe { buffer.write_buffer() };
        self.payload.adc.set_receive_address(ptr as u32);
        self.payload.adc.set_receive_counter(len as u16);

        compiler_fence(Ordering::Release);

        Transfer::w(buffer, self)
    }
}

impl TransferPayload for AdcDma<SingleSequence> {
    fn start(&mut self) {
        self.payload.adc.start_rx_pdc();
        self.payload.adc.start_conversion(); // Start ADC conversions
    }
    fn stop(&mut self) {
        self.payload.adc.stop_rx_pdc();
    }
    fn in_progress(&self) -> bool {
        self.payload.adc.rx_in_progress()
    }
}

impl TransferPayload for AdcDma<Continuous> {
    fn start(&mut self) {
        self.payload.adc.start_rx_pdc();
        self.payload.adc.enable_freerunning();
        self.payload.adc.start_conversion(); // Start ADC conversions
    }
    fn stop(&mut self) {
        self.payload.adc.disable_freerunning();
        self.payload.adc.stop_rx_pdc();
    }
    fn in_progress(&self) -> bool {
        self.payload.adc.rx_in_progress()
    }
}