ti-adc-expander 0.3.0

Async embedded-hal driver for the TI TLA2518/2528, ADS7038/7138, and ADS7028/7128 12-bit 8-channel ADC+GPIO expanders
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
#![no_std]
#![doc = include_str!("../README.md")]

use device_driver::{AsyncRegisterInterface, FieldsetMetadata, RegisterInterfaceBase};
use embedded_hal_async::{i2c::I2c, spi::SpiDevice};

// -- Chip typestates -----------------------------------------------------------

mod sealed {
    pub trait Chip {}
    pub trait ChannelMode {}
}

/// Marker trait implemented by all supported chips in this family.
pub trait Chip: sealed::Chip {}

/// TLA2518 (SPI) / TLA2528 (I2C): base feature set.
/// Supports ADC conversion, GPIO, oversampling, and sequencing.
/// No alert output, no statistics registers, no DWC.
pub struct Tla252x;

/// ADS7038 (SPI) / ADS7138 (I2C): adds digital window comparator, per-channel
/// alert thresholds, statistics (min/max/recent) registers, and GPO trigger.
pub struct Ads7x38;

/// ADS7028 (SPI) / ADS7128 (I2C): full feature set, adds RMS computation and
/// zero-crossing detection on top of all ADS7x38 capabilities.
pub struct Ads7x28;

impl sealed::Chip for Tla252x {}
impl sealed::Chip for Ads7x38 {}
impl sealed::Chip for Ads7x28 {}
impl Chip for Tla252x {}
impl Chip for Ads7x38 {}
impl Chip for Ads7x28 {}

/// Implemented by chips with alert output, digital window comparator, threshold
/// registers, and statistics (min/max/recent): ADS7x38 and ADS7x28.
pub trait HasStats: Chip {}
impl HasStats for Ads7x38 {}
impl HasStats for Ads7x28 {}

/// Implemented by chips with RMS computation and zero-crossing detection:
/// ADS7x28 only.
pub trait HasRmsZcd: HasStats {}
impl HasRmsZcd for Ads7x28 {}

// -- ZCD GPO value type --------------------------------------------------------

/// GPO output value applied on a zero-crossing detection edge (rise/fall).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ZcdGpoValue {
    Rise0Fall0 = 0,
    Rise0Fall1 = 1,
    Rise1Fall0 = 2,
    Rise1Fall1 = 3,
}

impl From<u8> for ZcdGpoValue {
    fn from(v: u8) -> Self {
        match v & 0x3 {
            0 => Self::Rise0Fall0,
            1 => Self::Rise0Fall1,
            2 => Self::Rise1Fall0,
            _ => Self::Rise1Fall1,
        }
    }
}

impl From<ZcdGpoValue> for u8 {
    fn from(v: ZcdGpoValue) -> Self {
        v as u8
    }
}

// -- Register map --------------------------------------------------------------

device_driver::compile!(
    options: "--rust-defmt-feature=defmt",
    manifest: "device.ddsl",
);

// -- I2C address ---------------------------------------------------------------

/// I2C address as set by the R1/R2 resistors on the ADDR pin.
/// See datasheet Table 1.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Address {
    /// R1 = DNP,    R2 = DNP   (default)
    X10 = 0x10,
    /// R1 = DNP,    R2 = 11 kOhm
    X11 = 0x11,
    /// R1 = DNP,    R2 = 33 kOhm
    X12 = 0x12,
    /// R1 = DNP,    R2 = 100 kOhm
    X13 = 0x13,
    /// R1 = 100 kOhm, R2 = DNP
    X14 = 0x14,
    /// R1 = 33 kOhm,  R2 = DNP
    X15 = 0x15,
    /// R1 = 11 kOhm,  R2 = DNP
    X16 = 0x16,
    /// R1 = 0 Ohm,    R2 = DNP
    X17 = 0x17,
}

// -- Bus interfaces ------------------------------------------------------------

const OPCODE_READ: u8 = 0x10;
const OPCODE_WRITE: u8 = 0x08;
/// Register address for MANUAL_CH_SEL (section 7.4.2 manual mode channel selection).
const REG_MANUAL_CH_SEL: u8 = 0x11;

/// I2C bus interface. Used by TLA2528, ADS7138, ADS7128.
pub struct I2cInterface<BUS> {
    i2c: BUS,
    addr: Address,
}

impl<BUS: I2c> RegisterInterfaceBase for I2cInterface<BUS> {
    type Error = BUS::Error;
    type AddressType = u8;
}

impl<BUS: I2c> AsyncRegisterInterface for I2cInterface<BUS> {
    async fn write_register(
        &mut self,
        address: u8,
        data: &mut [u8],
        _metadata: &FieldsetMetadata,
    ) -> Result<(), Self::Error> {
        self.i2c
            .write(self.addr as u8, &[OPCODE_WRITE, address, data[0]])
            .await
    }

    async fn read_register(
        &mut self,
        address: u8,
        data: &mut [u8],
        _metadata: &FieldsetMetadata,
    ) -> Result<(), Self::Error> {
        self.i2c
            .write_read(self.addr as u8, &[OPCODE_READ, address], data)
            .await
    }
}

/// SPI bus interface. Used by TLA2518, ADS7038, ADS7038H, ADS7028.
pub struct SpiInterface<SPI> {
    spi: SPI,
}

impl<SPI: SpiDevice> RegisterInterfaceBase for SpiInterface<SPI> {
    type Error = SPI::Error;
    type AddressType = u8;
}

impl<SPI: SpiDevice> AsyncRegisterInterface for SpiInterface<SPI> {
    async fn write_register(
        &mut self,
        address: u8,
        data: &mut [u8],
        _metadata: &FieldsetMetadata,
    ) -> Result<(), Self::Error> {
        // 24-bit write frame: [opcode, address, data] (section 7.3.12.2)
        self.spi.write(&[OPCODE_WRITE, address, data[0]]).await
    }

    async fn read_register(
        &mut self,
        address: u8,
        data: &mut [u8],
        _metadata: &FieldsetMetadata,
    ) -> Result<(), Self::Error> {
        // Two-frame register read (section 7.3.12.2):
        // Frame 1: issue read command; device latches requested register on CS rise.
        self.spi.write(&[OPCODE_READ, address, 0x00]).await?;
        // Frame 2: first SDO byte is the register data.
        self.spi.read(&mut data[..1]).await
    }
}

// -- CanConvert: raw ADC output frame read -------------------------------------
//
// Sealed trait implemented by both interfaces. Provides the bus-level primitive
// that `read_chN` dispatches through.
//
// Return value is the raw 16-bit MSB-aligned ADC word:
//   OSR = 0 (no averaging): 12-bit result in bits [15:4]; bits [3:0] = 0.
//   OSR > 0 (averaging):    full 16-bit result in bits [15:0].

/// Low-level trait for raw ADC output frame reads.
///
/// Implemented by [`I2cInterface`] (SCL-stretch conversion) and [`SpiInterface`]
/// (on-the-fly mode, section 7.4.3). Implement this for custom bus wrappers.
///
/// The returned `u16` is MSB-aligned:
/// - OSR = 0: 12-bit result in bits \[15:4\]; bits \[3:0\] = 0.
/// - OSR > 0: full 16-bit averaged result in bits \[15:0\].
#[allow(async_fn_in_trait)]
pub trait CanConvert: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface {
    /// Select `channel` (0-7) and return the raw 16-bit MSB-aligned ADC word.
    async fn read_conversion_raw(&mut self, channel: u8) -> Result<u16, Self::Error>;

    /// Read `out.len() / 2` consecutive conversion results in a *single* bus
    /// transaction, for auto-sequence mode (see
    /// [`Driver::read_analog_sequence`]).
    ///
    /// `out` must have even length. On SPI its contents are clocked out as they
    /// are read, so callers zero it first; the device ignores SDI in sequence
    /// mode.
    async fn read_sequence_raw(&mut self, out: &mut [u8]) -> Result<(), Self::Error>;
}

impl<BUS: I2c> CanConvert for I2cInterface<BUS> {
    async fn read_conversion_raw(&mut self, channel: u8) -> Result<u16, BUS::Error> {
        // Write MANUAL_CH_SEL so the device converts the right channel.
        self.write_register(
            REG_MANUAL_CH_SEL,
            &mut [channel & 0x0F],
            &device_driver::FieldsetMetadata::DEFAULT,
        )
        .await?;
        // Bare I2C read: device stretches SCL while converting (~1.17 us @ 1 MHz).
        let mut buf = [0u8; 2];
        self.i2c.read(self.addr as u8, &mut buf).await?;
        Ok((buf[0] as u16) << 8 | buf[1] as u16)
    }

    async fn read_sequence_raw(&mut self, out: &mut [u8]) -> Result<(), BUS::Error> {
        // One continuous read: the device advances to the next channel in the
        // sequence on each pair of bytes clocked out.
        self.i2c.read(self.addr as u8, out).await
    }
}

impl<SPI: SpiDevice> CanConvert for SpiInterface<SPI> {
    async fn read_conversion_raw(&mut self, channel: u8) -> Result<u16, SPI::Error> {
        // On-the-fly mode (section 7.4.3): channel ID in the first 5 SDI bits.
        // ADC samples the newly selected channel on the CS edge (zero latency).
        let mut buf = [(channel & 0x1F) << 3, 0x00];
        self.spi.transfer_in_place(&mut buf).await?;
        Ok((buf[0] as u16) << 8 | buf[1] as u16)
    }

    async fn read_sequence_raw(&mut self, out: &mut [u8]) -> Result<(), SPI::Error> {
        // A single CS-low transfer; the sequencer advances per 16-bit frame.
        self.spi.transfer_in_place(out).await
    }
}

// -- Channel mode types --------------------------------------------------------

/// Channel has not yet been configured.
pub struct Unconfigured;
/// Channel configured as an analog input.
pub struct AnalogIn;
/// Channel configured as a digital input (GPIO).
pub struct DigitalIn;
/// Channel configured as a digital output (GPIO). `DRIVE` is [`PushPull`] or [`OpenDrain`].
pub struct DigitalOut<DRIVE>(core::marker::PhantomData<DRIVE>);
/// Open-drain drive mode for [`DigitalOut`].
pub struct OpenDrain;
/// Push-pull drive mode for [`DigitalOut`].
pub struct PushPull;

/// Implemented by every channel typestate, exposing at compile time whether a
/// channel is an analog input.
///
/// This is what lets [`Driver::ANALOG_CHANNEL_MASK`] be an associated constant:
/// the set of channels to put in an auto-sequence is already encoded in the
/// driver's type, so it costs nothing at runtime and cannot disagree with how
/// the channels were actually configured.
pub trait ChannelMode: sealed::ChannelMode {
    /// Whether this channel takes part in ADC conversions.
    const IS_ANALOG: bool;
}

impl sealed::ChannelMode for Unconfigured {}
impl ChannelMode for Unconfigured {
    const IS_ANALOG: bool = false;
}
impl sealed::ChannelMode for AnalogIn {}
impl ChannelMode for AnalogIn {
    const IS_ANALOG: bool = true;
}
impl sealed::ChannelMode for DigitalIn {}
impl ChannelMode for DigitalIn {
    const IS_ANALOG: bool = false;
}
impl<DRIVE> sealed::ChannelMode for DigitalOut<DRIVE> {}
impl<DRIVE> ChannelMode for DigitalOut<DRIVE> {
    const IS_ANALOG: bool = false;
}

// -- Driver struct -------------------------------------------------------------

/// Core driver generic over bus interface (`IF`), chip capability tier (`CHIP`),
/// and the typestate of each of the 8 channels (`C0`-`C7`).
///
/// Use the part-number type aliases (`Ads7138<I2C>`, `Ads7038<SPI>`, etc.)
/// rather than constructing this type directly.
pub struct Driver<
    IF,
    CHIP,
    C0 = Unconfigured,
    C1 = Unconfigured,
    C2 = Unconfigured,
    C3 = Unconfigured,
    C4 = Unconfigured,
    C5 = Unconfigured,
    C6 = Unconfigured,
    C7 = Unconfigured,
> {
    pub device: Device<IF>,
    _chip: core::marker::PhantomData<CHIP>,
    // clippy::type_complexity fires on the eight-typestate tuple. Factoring it
    // behind an alias would satisfy the lint without telling a reader anything
    // the tuple doesn't already say — the arity *is* the meaning here, one
    // parameter per channel.
    #[allow(clippy::type_complexity)]
    _channels: core::marker::PhantomData<(C0, C1, C2, C3, C4, C5, C6, C7)>,
}

impl<BUS: I2c, CHIP: Chip> Driver<I2cInterface<BUS>, CHIP> {
    /// Create a new I2C driver. All channels start as `Unconfigured`.
    pub fn new(i2c: BUS, addr: Address) -> Self {
        Self {
            device: Device::new(I2cInterface { i2c, addr }),
            _chip: core::marker::PhantomData,
            _channels: core::marker::PhantomData,
        }
    }
}

impl<SPI: SpiDevice, CHIP: Chip> Driver<SpiInterface<SPI>, CHIP> {
    /// Create a new SPI driver. All channels start as `Unconfigured`.
    pub fn new(spi: SPI) -> Self {
        Self {
            device: Device::new(SpiInterface { spi }),
            _chip: core::marker::PhantomData,
            _channels: core::marker::PhantomData,
        }
    }
}

// -- Batch channel configuration -----------------------------------------------

/// Builder for batch channel configuration, returned by [`Driver::configure`].
///
/// Each `chN_as_*` call only updates local state (it's sync and infallible, no
/// bus access happens until [`Self::apply`]). `apply` then commits every
/// accumulated change with exactly one write per touched register (`PIN_CFG`,
/// `GPIO_CFG`, `GPO_DRIVE_CFG`), regardless of how many channels were staged.
///
/// ```ignore
/// let mut adc = adc
///     .configure()
///     .ch0_as_analog()
///     .ch2_as_analog()
///     .ch4_as_digital_out_push_pull()
///     .apply()
///     .await?;
/// ```
#[must_use = "staged channel configuration does nothing until `.apply()` is called"]
pub struct ConfigureChannels<
    IF,
    CHIP,
    C0 = Unconfigured,
    C1 = Unconfigured,
    C2 = Unconfigured,
    C3 = Unconfigured,
    C4 = Unconfigured,
    C5 = Unconfigured,
    C6 = Unconfigured,
    C7 = Unconfigured,
> {
    device: Device<IF>,
    pin_cfg_value: u8,
    pin_cfg_mask: u8,
    gpio_cfg_value: u8,
    gpio_cfg_mask: u8,
    gpo_drive_value: u8,
    gpo_drive_mask: u8,
    _chip: core::marker::PhantomData<CHIP>,
    // clippy::type_complexity fires on the eight-typestate tuple. Factoring it
    // behind an alias would satisfy the lint without telling a reader anything
    // the tuple doesn't already say — the arity *is* the meaning here, one
    // parameter per channel.
    #[allow(clippy::type_complexity)]
    _channels: core::marker::PhantomData<(C0, C1, C2, C3, C4, C5, C6, C7)>,
}

impl<IF, CHIP: Chip, C0, C1, C2, C3, C4, C5, C6, C7>
    Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
{
    /// Start a batch channel-configuration builder. No bus access happens until
    /// [`ConfigureChannels::apply`] is called on the result.
    pub fn configure(self) -> ConfigureChannels<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7> {
        ConfigureChannels {
            device: self.device,
            pin_cfg_value: 0,
            pin_cfg_mask: 0,
            gpio_cfg_value: 0,
            gpio_cfg_mask: 0,
            gpo_drive_value: 0,
            gpo_drive_mask: 0,
            _chip: core::marker::PhantomData,
            _channels: core::marker::PhantomData,
        }
    }
}

impl<
    IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface,
    CHIP: Chip,
    C0,
    C1,
    C2,
    C3,
    C4,
    C5,
    C6,
    C7,
> ConfigureChannels<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
{
    /// Commit all staged channel configuration, writing each touched register
    /// (`PIN_CFG`, `GPIO_CFG`, `GPO_DRIVE_CFG`) exactly once.
    pub async fn apply(
        mut self,
    ) -> Result<Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>, IF::Error> {
        let (mask, value) = (self.pin_cfg_mask, self.pin_cfg_value);
        if mask != 0 {
            self.device
                .pin_cfg()
                .modify_async(|r| r.set_pin_cfg((r.pin_cfg() & !mask) | (value & mask)))
                .await?;
        }
        let (mask, value) = (self.gpio_cfg_mask, self.gpio_cfg_value);
        if mask != 0 {
            self.device
                .gpio_cfg()
                .modify_async(|r| r.set_gpio_cfg((r.gpio_cfg() & !mask) | (value & mask)))
                .await?;
        }
        let (mask, value) = (self.gpo_drive_mask, self.gpo_drive_value);
        if mask != 0 {
            self.device
                .gpo_drive_cfg()
                .modify_async(|r| r.set_gpo_drive_cfg((r.gpo_drive_cfg() & !mask) | (value & mask)))
                .await?;
        }
        Ok(Driver {
            device: self.device,
            _chip: core::marker::PhantomData,
            _channels: core::marker::PhantomData,
        })
    }
}

// -- Global methods: all chips -------------------------------------------------

impl<
    IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface,
    CHIP: Chip,
    C0,
    C1,
    C2,
    C3,
    C4,
    C5,
    C6,
    C7,
> Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
{
    /// Reset all registers to defaults. Consumes the driver and returns a fresh
    /// instance with all channels in the `Unconfigured` state.
    pub async fn reset(mut self) -> Result<Driver<IF, CHIP>, IF::Error> {
        self.device
            .general_cfg()
            .write_with_zero_async(|r| r.set_rst(true))
            .await?;
        Ok(Driver {
            device: self.device,
            _chip: core::marker::PhantomData,
            _channels: core::marker::PhantomData,
        })
    }

    /// Initiate ADC offset calibration. The `cal` bit auto-clears when complete.
    pub async fn calibrate(&mut self) -> Result<(), IF::Error> {
        self.device
            .general_cfg()
            .modify_async(|r| r.set_cal(true))
            .await?;
        Ok(())
    }

    /// Whether the device has recorded a brown-out reset (`SYSTEM_STATUS.BOR`).
    ///
    /// Set on every power-up and latched until [`Self::clear_bor`] is called, so
    /// clearing it after configuration turns it into a reliable "did this device
    /// reset behind my back" flag.
    ///
    /// Worth checking periodically on any channel configured as a GPIO. A part
    /// that browns out and recovers still acknowledges its address and still
    /// returns plausible conversion results — but every register is back at its
    /// reset default, so channels configured as outputs have silently reverted
    /// to analog inputs and stopped driving. No I2C error is produced and no
    /// conversion looks wrong; this flag is the only signal that it happened.
    pub async fn browned_out(&mut self) -> Result<bool, IF::Error> {
        Ok(self.device.system_status().read_async().await?.bor())
    }

    /// Clear the brown-out reset indicator (W1C).
    pub async fn clear_bor(&mut self) -> Result<(), IF::Error> {
        self.device
            .system_status()
            .write_with_zero_async(|r| r.set_bor(true))
            .await?;
        Ok(())
    }

    /// Set the oversampling ratio applied to every conversion.
    pub async fn set_oversampling(&mut self, ratio: OversamplingRatio) -> Result<(), IF::Error> {
        self.device
            .osr_cfg()
            .modify_async(|r| r.set_osr(ratio))
            .await?;
        Ok(())
    }
}

// -- Auto-sequence conversion: all analog channels in one burst ----------------

impl<IF: CanConvert, CHIP: Chip, C0, C1, C2, C3, C4, C5, C6, C7>
    Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
where
    C0: ChannelMode,
    C1: ChannelMode,
    C2: ChannelMode,
    C3: ChannelMode,
    C4: ChannelMode,
    C5: ChannelMode,
    C6: ChannelMode,
    C7: ChannelMode,
{
    /// Bitmask of the channels this driver has configured as analog inputs,
    /// computed from the typestate at compile time.
    pub const ANALOG_CHANNEL_MASK: u8 = (C0::IS_ANALOG as u8)
        | (C1::IS_ANALOG as u8) << 1
        | (C2::IS_ANALOG as u8) << 2
        | (C3::IS_ANALOG as u8) << 3
        | (C4::IS_ANALOG as u8) << 4
        | (C5::IS_ANALOG as u8) << 5
        | (C6::IS_ANALOG as u8) << 6
        | (C7::IS_ANALOG as u8) << 7;

    /// Convert every channel configured as an analog input, returning results
    /// indexed by channel (`None` for channels that aren't analog inputs).
    ///
    /// Uses the device's auto-sequencer, so the whole set costs four bus
    /// transactions regardless of how many channels are enabled, against the two
    /// per channel that [`Driver::read_ch0`] and friends need (a `MANUAL_CH_SEL`
    /// write plus a conversion read each). For a board where bus activity is an
    /// RFI budget rather than a throughput concern, that difference is the point.
    ///
    /// The sequencer's mode is set up and torn back down around each call, so
    /// the device is left in manual mode and the per-channel `read_chN` methods
    /// keep working between calls, and `AUTO_SEQ_CH_SEL` is rewritten every time
    /// rather than cached — a device that reset behind the driver's back gets
    /// correct configuration on the next call instead of silently sequencing the
    /// wrong set.
    ///
    /// # Result attribution
    ///
    /// Results come back in ascending channel order and are attributed on that
    /// basis; the device does not tag them (the 4-bit channel ID that
    /// `DATA_CFG.APPEND_STATUS` can append occupies the low bits of a 12-bit
    /// result, so it is unavailable at any oversampling ratio above `Osr1`,
    /// where conversions use the full 16 bits). Mis-ordering would therefore
    /// swap readings between channels *silently*. Two things bound that risk:
    /// the entire sequence is consumed in one transaction and the sequencer is
    /// restarted on every call, so no misalignment can persist across calls; and
    /// [`Self::verify_analog_sequence_order`] checks the ordering against the
    /// device's own channel IDs, which is worth doing once at bring-up before
    /// trusting this on hardware you haven't run it on.
    pub async fn read_analog_sequence(&mut self) -> Result<[Option<u16>; 8], IF::Error> {
        let mask = Self::ANALOG_CHANNEL_MASK;
        let mut results = [None; 8];
        if mask == 0 {
            return Ok(results);
        }

        let count = mask.count_ones() as usize;
        let mut buf = [0u8; 16];
        self.run_analog_sequence(&mut buf[..count * 2]).await?;

        for (slot, channel) in (0..8u8).filter(|c| mask & (1 << c) != 0).enumerate() {
            let hi = buf[slot * 2] as u16;
            let lo = buf[slot * 2 + 1] as u16;
            results[channel as usize] = Some(hi << 8 | lo);
        }
        Ok(results)
    }

    /// Check that the auto-sequencer returns channels in the ascending order
    /// [`Self::read_analog_sequence`] assumes.
    ///
    /// Run once at bring-up, not periodically: it costs six bus transactions and
    /// briefly changes `OSR_CFG` and `DATA_CFG`, both of which are restored
    /// before returning. It works by dropping to `Osr1` — the one ratio that
    /// leaves the low four bits of a conversion free — and enabling
    /// `DATA_CFG.APPEND_STATUS = ChannelId`, so the device labels each result
    /// with the channel it came from, then confirming those labels match the
    /// enabled channels in ascending order.
    ///
    /// `Ok(false)` means the ordering assumption does not hold on this part and
    /// [`Self::read_analog_sequence`] would mis-attribute readings; fall back to
    /// the per-channel `read_chN` methods.
    pub async fn verify_analog_sequence_order(&mut self) -> Result<bool, IF::Error> {
        let mask = Self::ANALOG_CHANNEL_MASK;
        if mask == 0 {
            return Ok(true);
        }
        let count = mask.count_ones() as usize;

        let saved_osr = self.device.osr_cfg().read_async().await?.osr();
        self.device
            .osr_cfg()
            .modify_async(|r| r.set_osr(OversamplingRatio::Osr1))
            .await?;
        self.device
            .data_cfg()
            .modify_async(|r| r.set_append_status(AppendStatus::ChannelId))
            .await?;

        let mut buf = [0u8; 16];
        let sequence = self.run_analog_sequence(&mut buf[..count * 2]).await;

        // Restore first, unconditionally: leaving the device at Osr1 with status
        // bytes appended would corrupt every later reading far more quietly than
        // whatever made the sequence fail.
        self.device
            .data_cfg()
            .modify_async(|r| r.set_append_status(AppendStatus::None))
            .await?;
        self.device
            .osr_cfg()
            .modify_async(|r| r.set_osr(saved_osr))
            .await?;
        sequence?;

        let ordered = (0..8u8)
            .filter(|c| mask & (1 << c) != 0)
            .enumerate()
            .all(|(slot, channel)| buf[slot * 2 + 1] & 0x0F == channel);
        Ok(ordered)
    }

    /// Point the sequencer at the analog channels, run one pass into `out`, and
    /// put the device back in manual mode.
    async fn run_analog_sequence(&mut self, out: &mut [u8]) -> Result<(), IF::Error> {
        self.device
            .auto_seq_ch_sel()
            .write_async(|r| r.set_auto_seq_ch_sel(Self::ANALOG_CHANNEL_MASK))
            .await?;
        self.device
            .sequence_cfg()
            .write_async(|r| {
                r.set_seq_mode(SeqMode::AutoSequence);
                r.set_seq_start(true);
            })
            .await?;

        let read = self.device.interface.read_sequence_raw(out).await;

        // Always restore manual mode, even if the read failed: a device left
        // sequencing would make the next `read_chN` return some other channel.
        self.device
            .sequence_cfg()
            .write_async(|r| {
                r.set_seq_mode(SeqMode::Manual);
                r.set_seq_start(false);
            })
            .await?;
        read
    }
}

// -- Global methods: HasStats chips (ADS7x38, ADS7x28) ------------------------

impl<
    IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface,
    CHIP: HasStats,
    C0,
    C1,
    C2,
    C3,
    C4,
    C5,
    C6,
    C7,
> Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
{
    /// Enable the digital window comparator.
    pub async fn enable_dwc(&mut self) -> Result<(), IF::Error> {
        self.device
            .general_cfg()
            .modify_async(|r| r.set_dwc_en(true))
            .await?;
        Ok(())
    }

    /// Disable the digital window comparator.
    pub async fn disable_dwc(&mut self) -> Result<(), IF::Error> {
        self.device
            .general_cfg()
            .modify_async(|r| r.set_dwc_en(false))
            .await?;
        Ok(())
    }

    /// Configure the ALERT pin driver type and assertion logic.
    pub async fn configure_alert_pin(
        &mut self,
        push_pull: bool,
        logic: AlertLogic,
    ) -> Result<(), IF::Error> {
        self.device
            .alert_pin_cfg()
            .write_with_zero_async(|r| {
                r.set_alert_drive(push_pull);
                r.set_alert_logic(logic);
            })
            .await?;
        Ok(())
    }

    /// Set which channels can assert the ALERT pin (bit N = 1 enables CH\[N\]).
    pub async fn set_alert_channel_mask(&mut self, mask: u8) -> Result<(), IF::Error> {
        self.device
            .alert_ch_sel()
            .write_with_zero_async(|r| r.set_alert_ch_sel(mask))
            .await?;
        Ok(())
    }

    /// Read the combined event flags register (bit N = OR of high and low flags for CH\[N\]).
    pub async fn event_flags(&mut self) -> Result<u8, IF::Error> {
        Ok(self.device.event_flag().read_async().await?.event_flag())
    }

    /// Read the high-threshold (or GPIO logic-1) event flags.
    pub async fn event_high_flags(&mut self) -> Result<u8, IF::Error> {
        Ok(self
            .device
            .event_high_flag()
            .read_async()
            .await?
            .event_high_flag())
    }

    /// Read the low-threshold (or GPIO logic-0) event flags.
    pub async fn event_low_flags(&mut self) -> Result<u8, IF::Error> {
        Ok(self
            .device
            .event_low_flag()
            .read_async()
            .await?
            .event_low_flag())
    }

    /// Clear high-event flags for the given channel bitmask (W1C).
    pub async fn clear_event_high_flags(&mut self, mask: u8) -> Result<(), IF::Error> {
        self.device
            .event_high_flag()
            .write_with_zero_async(|r| r.set_event_high_flag(mask))
            .await?;
        Ok(())
    }

    /// Clear low-event flags for the given channel bitmask (W1C).
    pub async fn clear_event_low_flags(&mut self, mask: u8) -> Result<(), IF::Error> {
        self.device
            .event_low_flag()
            .write_with_zero_async(|r| r.set_event_low_flag(mask))
            .await?;
        Ok(())
    }
}

// -- Global methods: HasRmsZcd chips (ADS7x28) --------------------------------

impl<
    IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface,
    CHIP: HasRmsZcd,
    C0,
    C1,
    C2,
    C3,
    C4,
    C5,
    C6,
    C7,
> Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
{
    /// Configure the RMS computation module.
    ///
    /// `channel` selects which AIN is measured; `dc_sub` subtracts the DC
    /// component before computing; `samples` sets the accumulation window.
    /// Call `enable_dwc()` (which also enables the statistics module) before
    /// reading results.
    pub async fn configure_rms(
        &mut self,
        channel: RmsChannelId,
        dc_sub: bool,
        samples: RmsSampleCount,
    ) -> Result<(), IF::Error> {
        self.device
            .rms_cfg()
            .write_with_zero_async(|r| {
                r.set_rms_chid(channel);
                r.set_rms_dc_sub(dc_sub);
                r.set_rms_samples(samples);
            })
            .await?;
        Ok(())
    }

    /// Read the 16-bit RMS result.
    pub async fn read_rms(&mut self) -> Result<u16, IF::Error> {
        let lsb = self.device.rms_lsb().read_async().await?.value();
        let msb = self.device.rms_msb().read_async().await?.value();
        Ok(((msb as u16) << 8) | lsb as u16)
    }

    /// Configure the zero-crossing detection blanking time.
    ///
    /// `multiplier_8x`: false = 1x blanking, true = 8x blanking.
    /// `blanking`: 7-bit blanking count value.
    pub async fn configure_zcd_blanking(
        &mut self,
        multiplier_8x: bool,
        blanking: u8,
    ) -> Result<(), IF::Error> {
        self.device
            .zcd_blanking_cfg()
            .write_with_zero_async(|r| {
                r.set_mult_en(multiplier_8x);
                r.set_zcd_blanking(blanking & 0x7F);
            })
            .await?;
        Ok(())
    }

    /// Set the GPO value driven on ZCD edge detection for channels 0-3.
    pub async fn set_zcd_gpo_ch0_ch3(
        &mut self,
        ch0: ZcdGpoValue,
        ch1: ZcdGpoValue,
        ch2: ZcdGpoValue,
        ch3: ZcdGpoValue,
    ) -> Result<(), IF::Error> {
        self.device
            .gpo_value_zcd_cfg_ch_0_ch_3()
            .write_with_zero_async(|r| {
                r.set_ch_0(ch0);
                r.set_ch_1(ch1);
                r.set_ch_2(ch2);
                r.set_ch_3(ch3);
            })
            .await?;
        Ok(())
    }

    /// Set the GPO value driven on ZCD edge detection for channels 4-7.
    pub async fn set_zcd_gpo_ch4_ch7(
        &mut self,
        ch4: ZcdGpoValue,
        ch5: ZcdGpoValue,
        ch6: ZcdGpoValue,
        ch7: ZcdGpoValue,
    ) -> Result<(), IF::Error> {
        self.device
            .gpo_value_zcd_cfg_ch_4_ch_7()
            .write_with_zero_async(|r| {
                r.set_ch_4(ch4);
                r.set_ch_5(ch5);
                r.set_ch_6(ch6);
                r.set_ch_7(ch7);
            })
            .await?;
        Ok(())
    }

    /// Set which GPO outputs are updated on zero-crossing detection (bit N = 1 enables GPO\[N\]).
    pub async fn set_zcd_gpo_update_mask(&mut self, mask: u8) -> Result<(), IF::Error> {
        self.device
            .gpo_zcd_update_en()
            .write_with_zero_async(|r| r.set_gpo_zcd_update_en(mask))
            .await?;
        Ok(())
    }
}

// -- Per-channel typestate impl ------------------------------------------------

/// Generates configure/read/write impls for one channel.
///
/// Arguments:
///   $n:    channel index literal (0-7)
///   $pre:  channel type params that come *before* channel $n in the struct
///   $post: channel type params that come *after* channel $n in the struct
macro_rules! impl_channel {
    ($n:literal, ($($pre:ident),*), ($($post:ident),*)) => {
        pastey::paste! {
            // -- configure (from any current mode, any chip): pure bit twiddling, --
            // -- no bus access; staged into the ConfigureChannels builder ----------

            impl<IF, CHIP: Chip, [<C $n>] $(, $pre)* $(, $post)*>
                ConfigureChannels<IF, CHIP, $($pre,)* [<C $n>], $($post,)*>
            {
                #[doc = concat!("Stage channel ", stringify!($n), " as an analog input.")]
                pub fn [<ch $n _as_analog>](mut self)
                    -> ConfigureChannels<IF, CHIP, $($pre,)* AnalogIn, $($post,)*>
                {
                    self.pin_cfg_mask |= 1u8 << $n;
                    self.pin_cfg_value &= !(1u8 << $n);
                    ConfigureChannels {
                        device: self.device,
                        pin_cfg_value: self.pin_cfg_value,
                        pin_cfg_mask: self.pin_cfg_mask,
                        gpio_cfg_value: self.gpio_cfg_value,
                        gpio_cfg_mask: self.gpio_cfg_mask,
                        gpo_drive_value: self.gpo_drive_value,
                        gpo_drive_mask: self.gpo_drive_mask,
                        _chip: core::marker::PhantomData,
                        _channels: core::marker::PhantomData,
                    }
                }

                #[doc = concat!("Stage channel ", stringify!($n), " as a digital input (GPIO).")]
                pub fn [<ch $n _as_digital_in>](mut self)
                    -> ConfigureChannels<IF, CHIP, $($pre,)* DigitalIn, $($post,)*>
                {
                    self.pin_cfg_mask |= 1u8 << $n;
                    self.pin_cfg_value |= 1u8 << $n;
                    self.gpio_cfg_mask |= 1u8 << $n;
                    self.gpio_cfg_value &= !(1u8 << $n);
                    ConfigureChannels {
                        device: self.device,
                        pin_cfg_value: self.pin_cfg_value,
                        pin_cfg_mask: self.pin_cfg_mask,
                        gpio_cfg_value: self.gpio_cfg_value,
                        gpio_cfg_mask: self.gpio_cfg_mask,
                        gpo_drive_value: self.gpo_drive_value,
                        gpo_drive_mask: self.gpo_drive_mask,
                        _chip: core::marker::PhantomData,
                        _channels: core::marker::PhantomData,
                    }
                }

                #[doc = concat!("Stage channel ", stringify!($n), " as a push-pull digital output (GPIO).")]
                pub fn [<ch $n _as_digital_out_push_pull>](mut self)
                    -> ConfigureChannels<IF, CHIP, $($pre,)* DigitalOut<PushPull>, $($post,)*>
                {
                    self.pin_cfg_mask |= 1u8 << $n;
                    self.pin_cfg_value |= 1u8 << $n;
                    self.gpio_cfg_mask |= 1u8 << $n;
                    self.gpio_cfg_value |= 1u8 << $n;
                    self.gpo_drive_mask |= 1u8 << $n;
                    self.gpo_drive_value |= 1u8 << $n;
                    ConfigureChannels {
                        device: self.device,
                        pin_cfg_value: self.pin_cfg_value,
                        pin_cfg_mask: self.pin_cfg_mask,
                        gpio_cfg_value: self.gpio_cfg_value,
                        gpio_cfg_mask: self.gpio_cfg_mask,
                        gpo_drive_value: self.gpo_drive_value,
                        gpo_drive_mask: self.gpo_drive_mask,
                        _chip: core::marker::PhantomData,
                        _channels: core::marker::PhantomData,
                    }
                }

                #[doc = concat!("Stage channel ", stringify!($n), " as an open-drain digital output (GPIO).")]
                pub fn [<ch $n _as_digital_out_open_drain>](mut self)
                    -> ConfigureChannels<IF, CHIP, $($pre,)* DigitalOut<OpenDrain>, $($post,)*>
                {
                    self.pin_cfg_mask |= 1u8 << $n;
                    self.pin_cfg_value |= 1u8 << $n;
                    self.gpio_cfg_mask |= 1u8 << $n;
                    self.gpio_cfg_value |= 1u8 << $n;
                    self.gpo_drive_mask |= 1u8 << $n;
                    self.gpo_drive_value &= !(1u8 << $n);
                    ConfigureChannels {
                        device: self.device,
                        pin_cfg_value: self.pin_cfg_value,
                        pin_cfg_mask: self.pin_cfg_mask,
                        gpio_cfg_value: self.gpio_cfg_value,
                        gpio_cfg_mask: self.gpio_cfg_mask,
                        gpo_drive_value: self.gpo_drive_value,
                        gpo_drive_mask: self.gpo_drive_mask,
                        _chip: core::marker::PhantomData,
                        _channels: core::marker::PhantomData,
                    }
                }
            }

            // -- AnalogIn: SCL-stretch (I2C) / on-the-fly (SPI) read ------
            //
            // Available on all chips. For I2C, the device stretches SCL during
            // conversion. For SPI, uses on-the-fly mode (section 7.4.3), no latency.
            //
            // Returns the raw 16-bit MSB-aligned ADC word:
            //   OSR = 0: 12-bit result in bits [15:4]; bits [3:0] = 0.
            //   OSR > 0: full 16-bit averaged result in bits [15:0].

            impl<IF: CanConvert, CHIP: Chip $(, $pre)* $(, $post)*>
                Driver<IF, CHIP, $($pre,)* AnalogIn, $($post,)*>
            {
                pub async fn [<read_ch $n>](&mut self) -> Result<u16, IF::Error> {
                    self.device.interface.read_conversion_raw($n).await
                }
            }

            // -- AnalogIn: polled read + thresholds (HasStats chips only) --

            impl<IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface, CHIP: HasStats $(, $pre)* $(, $post)*>
                Driver<IF, CHIP, $($pre,)* AnalogIn, $($post,)*>
            {
                #[doc = concat!("Trigger a conversion on channel ", stringify!($n), " without SCL stretching and")]
                /// return the raw 16-bit MSB-aligned ADC word.
                ///
                /// Enables STATS_EN, triggers the conversion via CNVST, polls
                #[doc = concat!("OSR_DONE, then reads the result from the RECENT_CH", stringify!($n), " registers.")]
                ///
                /// Returns the raw 16-bit MSB-aligned ADC word:
                ///   OSR = 0: 12-bit result in bits \[15:4\]; bits \[3:0\] = 0.
                ///   OSR > 0: full 16-bit averaged result in bits \[15:0\].
                pub async fn [<read_ch $n _polled>](&mut self) -> Result<u16, IF::Error> {
                    self.device.general_cfg().modify_async(|r| r.set_stats_en(true)).await?;
                    self.device.manual_ch_sel().write_async(|r| {
                        r.set_manual_chid(ChannelId::[<Ain $n>])
                    }).await?;
                    self.device.general_cfg().modify_async(|r| r.set_cnvst(true)).await?;
                    loop {
                        if self.device.system_status().read_async().await?.osr_done() {
                            break;
                        }
                    }
                    self.device.system_status().write_with_zero_async(|r| {
                        r.set_osr_done(true)
                    }).await?;
                    let lsb = self.device.recent_ch_lsb().read_at_async($n).await?.value();
                    let msb = self.device.recent_ch_msb().read_at_async($n).await?.value();
                    Ok(((msb as u16) << 8) | lsb as u16)
                }

                #[doc = concat!("Set the high and low alert thresholds for channel ", stringify!($n), " (12-bit, 0-4095).")]
                pub async fn [<set_ch $n _thresholds>](
                    &mut self,
                    high: u16,
                    low: u16,
                ) -> Result<(), IF::Error> {
                    self.device
                        .high_th_ch()
                        .write_with_zero_at_async($n, |r| r.set_high_threshold_msb((high >> 4) as u8))
                        .await?;
                    self.device
                        .hysteresis_ch()
                        .modify_at_async($n, |r| r.set_high_threshold_lsb((high & 0xF) as u8))
                        .await?;
                    self.device
                        .low_th_ch()
                        .write_with_zero_at_async($n, |r| r.set_low_threshold_msb((low >> 4) as u8))
                        .await?;
                    self.device
                        .event_count_ch()
                        .modify_at_async($n, |r| r.set_low_threshold_lsb((low & 0xF) as u8))
                        .await?;
                    Ok(())
                }

                #[doc = concat!("Set the hysteresis for channel ", stringify!($n), " (4-bit; effective value = `hyst << 3` LSBs).")]
                pub async fn [<set_ch $n _hysteresis>](
                    &mut self,
                    hyst: u8,
                ) -> Result<(), IF::Error> {
                    self.device
                        .hysteresis_ch()
                        .modify_at_async($n, |r| r.set_hysteresis(hyst & 0xF))
                        .await?;
                    Ok(())
                }

                #[doc = concat!("Set the event count for channel ", stringify!($n), " (4-bit; alert fires after `count + 1`")]
                /// consecutive threshold violations).
                pub async fn [<set_ch $n _event_count>](
                    &mut self,
                    count: u8,
                ) -> Result<(), IF::Error> {
                    self.device
                        .event_count_ch()
                        .modify_at_async($n, |r| r.set_event_count(count & 0xF))
                        .await?;
                    Ok(())
                }
            }

            // -- DigitalIn: read (all chips) -------------------------------

            impl<IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface, CHIP: Chip $(, $pre)* $(, $post)*>
                Driver<IF, CHIP, $($pre,)* DigitalIn, $($post,)*>
            {
                pub async fn [<is_ch $n _high>](&mut self) -> Result<bool, IF::Error> {
                    Ok(self.device.gpi_value().read_async().await?.gpi_value() & (1u8 << $n) != 0)
                }
            }

            // -- DigitalOut: write (all chips) -----------------------------

            impl<IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface, CHIP: Chip, D $(, $pre)* $(, $post)*>
                Driver<IF, CHIP, $($pre,)* DigitalOut<D>, $($post,)*>
            {
                pub async fn [<write_ch $n>](&mut self, high: bool) -> Result<(), IF::Error> {
                    self.device.gpo_value().modify_async(|r| {
                        let v = r.gpo_value();
                        r.set_gpo_value(if high { v | (1u8 << $n) } else { v & !(1u8 << $n) })
                    }).await?;
                    Ok(())
                }
            }
        }
    }
}

impl_channel!(0, (), (C1, C2, C3, C4, C5, C6, C7));
impl_channel!(1, (C0), (C2, C3, C4, C5, C6, C7));
impl_channel!(2, (C0, C1), (C3, C4, C5, C6, C7));
impl_channel!(3, (C0, C1, C2), (C4, C5, C6, C7));
impl_channel!(4, (C0, C1, C2, C3), (C5, C6, C7));
impl_channel!(5, (C0, C1, C2, C3, C4), (C6, C7));
impl_channel!(6, (C0, C1, C2, C3, C4, C5), (C7));
impl_channel!(7, (C0, C1, C2, C3, C4, C5, C6), ());

// -- Per-part-number type aliases ----------------------------------------------

macro_rules! chip_alias {
    ($bus:ident : $(#[$attr:meta])* $name:ident, $chip:ty) => {
        pastey::paste! {
            $(#[$attr])*
            pub type $name<
                BUS,
                C0 = Unconfigured,
                C1 = Unconfigured,
                C2 = Unconfigured,
                C3 = Unconfigured,
                C4 = Unconfigured,
                C5 = Unconfigured,
                C6 = Unconfigured,
                C7 = Unconfigured,
            > = Driver<[<$bus:camel Interface>]<BUS>, $chip, C0, C1, C2, C3, C4, C5, C6, C7>;
        }
    };
}

chip_alias!(i2c: Tla2528, Tla252x);
chip_alias!(spi: Tla2518, Tla252x);
chip_alias!(i2c: Ads7138, Ads7x38);
chip_alias!(spi: Ads7038, Ads7x38);
chip_alias!(spi:
    /// ADS7038H is a higher-throughput (1.5 MSPS vs 1 MSPS) SPI variant of the ADS7038.
    /// The register map and feature set are identical; the speed difference is a hardware
    /// characteristic with no register-level impact.
    Ads7038H,
    Ads7x38
);
chip_alias!(i2c: Ads7128, Ads7x28);
chip_alias!(spi: Ads7028, Ads7x28);