Skip to main content

ti_adc_expander/
lib.rs

1#![no_std]
2#![doc = include_str!("../README.md")]
3
4use device_driver::{AsyncRegisterInterface, FieldsetMetadata, RegisterInterfaceBase};
5use embedded_hal_async::{i2c::I2c, spi::SpiDevice};
6
7// -- Chip typestates -----------------------------------------------------------
8
9mod sealed {
10    pub trait Chip {}
11    pub trait ChannelMode {}
12}
13
14/// Marker trait implemented by all supported chips in this family.
15pub trait Chip: sealed::Chip {}
16
17/// TLA2518 (SPI) / TLA2528 (I2C): base feature set.
18/// Supports ADC conversion, GPIO, oversampling, and sequencing.
19/// No alert output, no statistics registers, no DWC.
20pub struct Tla252x;
21
22/// ADS7038 (SPI) / ADS7138 (I2C): adds digital window comparator, per-channel
23/// alert thresholds, statistics (min/max/recent) registers, and GPO trigger.
24pub struct Ads7x38;
25
26/// ADS7028 (SPI) / ADS7128 (I2C): full feature set, adds RMS computation and
27/// zero-crossing detection on top of all ADS7x38 capabilities.
28pub struct Ads7x28;
29
30impl sealed::Chip for Tla252x {}
31impl sealed::Chip for Ads7x38 {}
32impl sealed::Chip for Ads7x28 {}
33impl Chip for Tla252x {}
34impl Chip for Ads7x38 {}
35impl Chip for Ads7x28 {}
36
37/// Implemented by chips with alert output, digital window comparator, threshold
38/// registers, and statistics (min/max/recent): ADS7x38 and ADS7x28.
39pub trait HasStats: Chip {}
40impl HasStats for Ads7x38 {}
41impl HasStats for Ads7x28 {}
42
43/// Implemented by chips with RMS computation and zero-crossing detection:
44/// ADS7x28 only.
45pub trait HasRmsZcd: HasStats {}
46impl HasRmsZcd for Ads7x28 {}
47
48// -- ZCD GPO value type --------------------------------------------------------
49
50/// GPO output value applied on a zero-crossing detection edge (rise/fall).
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52#[cfg_attr(feature = "defmt", derive(defmt::Format))]
53pub enum ZcdGpoValue {
54    Rise0Fall0 = 0,
55    Rise0Fall1 = 1,
56    Rise1Fall0 = 2,
57    Rise1Fall1 = 3,
58}
59
60impl From<u8> for ZcdGpoValue {
61    fn from(v: u8) -> Self {
62        match v & 0x3 {
63            0 => Self::Rise0Fall0,
64            1 => Self::Rise0Fall1,
65            2 => Self::Rise1Fall0,
66            _ => Self::Rise1Fall1,
67        }
68    }
69}
70
71impl From<ZcdGpoValue> for u8 {
72    fn from(v: ZcdGpoValue) -> Self {
73        v as u8
74    }
75}
76
77// -- Register map --------------------------------------------------------------
78
79device_driver::compile!(
80    options: "--rust-defmt-feature=defmt",
81    manifest: "device.ddsl",
82);
83
84// -- I2C address ---------------------------------------------------------------
85
86/// I2C address as set by the R1/R2 resistors on the ADDR pin.
87/// See datasheet Table 1.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89#[cfg_attr(feature = "defmt", derive(defmt::Format))]
90pub enum Address {
91    /// R1 = DNP,    R2 = DNP   (default)
92    X10 = 0x10,
93    /// R1 = DNP,    R2 = 11 kOhm
94    X11 = 0x11,
95    /// R1 = DNP,    R2 = 33 kOhm
96    X12 = 0x12,
97    /// R1 = DNP,    R2 = 100 kOhm
98    X13 = 0x13,
99    /// R1 = 100 kOhm, R2 = DNP
100    X14 = 0x14,
101    /// R1 = 33 kOhm,  R2 = DNP
102    X15 = 0x15,
103    /// R1 = 11 kOhm,  R2 = DNP
104    X16 = 0x16,
105    /// R1 = 0 Ohm,    R2 = DNP
106    X17 = 0x17,
107}
108
109// -- Bus interfaces ------------------------------------------------------------
110
111const OPCODE_READ: u8 = 0x10;
112const OPCODE_WRITE: u8 = 0x08;
113/// Register address for MANUAL_CH_SEL (section 7.4.2 manual mode channel selection).
114const REG_MANUAL_CH_SEL: u8 = 0x11;
115
116/// I2C bus interface. Used by TLA2528, ADS7138, ADS7128.
117pub struct I2cInterface<BUS> {
118    i2c: BUS,
119    addr: Address,
120}
121
122impl<BUS: I2c> RegisterInterfaceBase for I2cInterface<BUS> {
123    type Error = BUS::Error;
124    type AddressType = u8;
125}
126
127impl<BUS: I2c> AsyncRegisterInterface for I2cInterface<BUS> {
128    async fn write_register(
129        &mut self,
130        address: u8,
131        data: &mut [u8],
132        _metadata: &FieldsetMetadata,
133    ) -> Result<(), Self::Error> {
134        self.i2c
135            .write(self.addr as u8, &[OPCODE_WRITE, address, data[0]])
136            .await
137    }
138
139    async fn read_register(
140        &mut self,
141        address: u8,
142        data: &mut [u8],
143        _metadata: &FieldsetMetadata,
144    ) -> Result<(), Self::Error> {
145        self.i2c
146            .write_read(self.addr as u8, &[OPCODE_READ, address], data)
147            .await
148    }
149}
150
151/// SPI bus interface. Used by TLA2518, ADS7038, ADS7038H, ADS7028.
152pub struct SpiInterface<SPI> {
153    spi: SPI,
154}
155
156impl<SPI: SpiDevice> RegisterInterfaceBase for SpiInterface<SPI> {
157    type Error = SPI::Error;
158    type AddressType = u8;
159}
160
161impl<SPI: SpiDevice> AsyncRegisterInterface for SpiInterface<SPI> {
162    async fn write_register(
163        &mut self,
164        address: u8,
165        data: &mut [u8],
166        _metadata: &FieldsetMetadata,
167    ) -> Result<(), Self::Error> {
168        // 24-bit write frame: [opcode, address, data] (section 7.3.12.2)
169        self.spi.write(&[OPCODE_WRITE, address, data[0]]).await
170    }
171
172    async fn read_register(
173        &mut self,
174        address: u8,
175        data: &mut [u8],
176        _metadata: &FieldsetMetadata,
177    ) -> Result<(), Self::Error> {
178        // Two-frame register read (section 7.3.12.2):
179        // Frame 1: issue read command; device latches requested register on CS rise.
180        self.spi.write(&[OPCODE_READ, address, 0x00]).await?;
181        // Frame 2: first SDO byte is the register data.
182        self.spi.read(&mut data[..1]).await
183    }
184}
185
186// -- CanConvert: raw ADC output frame read -------------------------------------
187//
188// Sealed trait implemented by both interfaces. Provides the bus-level primitive
189// that `read_chN` dispatches through.
190//
191// Return value is the raw 16-bit MSB-aligned ADC word:
192//   OSR = 0 (no averaging): 12-bit result in bits [15:4]; bits [3:0] = 0.
193//   OSR > 0 (averaging):    full 16-bit result in bits [15:0].
194
195/// Low-level trait for raw ADC output frame reads.
196///
197/// Implemented by [`I2cInterface`] (SCL-stretch conversion) and [`SpiInterface`]
198/// (on-the-fly mode, section 7.4.3). Implement this for custom bus wrappers.
199///
200/// The returned `u16` is MSB-aligned:
201/// - OSR = 0: 12-bit result in bits \[15:4\]; bits \[3:0\] = 0.
202/// - OSR > 0: full 16-bit averaged result in bits \[15:0\].
203#[allow(async_fn_in_trait)]
204pub trait CanConvert: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface {
205    /// Select `channel` (0-7) and return the raw 16-bit MSB-aligned ADC word.
206    async fn read_conversion_raw(&mut self, channel: u8) -> Result<u16, Self::Error>;
207
208    /// Read `out.len() / 2` consecutive conversion results in a *single* bus
209    /// transaction, for auto-sequence mode (see
210    /// [`Driver::read_analog_sequence`]).
211    ///
212    /// `out` must have even length. On SPI its contents are clocked out as they
213    /// are read, so callers zero it first; the device ignores SDI in sequence
214    /// mode.
215    async fn read_sequence_raw(&mut self, out: &mut [u8]) -> Result<(), Self::Error>;
216}
217
218impl<BUS: I2c> CanConvert for I2cInterface<BUS> {
219    async fn read_conversion_raw(&mut self, channel: u8) -> Result<u16, BUS::Error> {
220        // Write MANUAL_CH_SEL so the device converts the right channel.
221        self.write_register(
222            REG_MANUAL_CH_SEL,
223            &mut [channel & 0x0F],
224            &device_driver::FieldsetMetadata::DEFAULT,
225        )
226        .await?;
227        // Bare I2C read: device stretches SCL while converting (~1.17 us @ 1 MHz).
228        let mut buf = [0u8; 2];
229        self.i2c.read(self.addr as u8, &mut buf).await?;
230        Ok((buf[0] as u16) << 8 | buf[1] as u16)
231    }
232
233    async fn read_sequence_raw(&mut self, out: &mut [u8]) -> Result<(), BUS::Error> {
234        // One continuous read: the device advances to the next channel in the
235        // sequence on each pair of bytes clocked out.
236        self.i2c.read(self.addr as u8, out).await
237    }
238}
239
240impl<SPI: SpiDevice> CanConvert for SpiInterface<SPI> {
241    async fn read_conversion_raw(&mut self, channel: u8) -> Result<u16, SPI::Error> {
242        // On-the-fly mode (section 7.4.3): channel ID in the first 5 SDI bits.
243        // ADC samples the newly selected channel on the CS edge (zero latency).
244        let mut buf = [(channel & 0x1F) << 3, 0x00];
245        self.spi.transfer_in_place(&mut buf).await?;
246        Ok((buf[0] as u16) << 8 | buf[1] as u16)
247    }
248
249    async fn read_sequence_raw(&mut self, out: &mut [u8]) -> Result<(), SPI::Error> {
250        // A single CS-low transfer; the sequencer advances per 16-bit frame.
251        self.spi.transfer_in_place(out).await
252    }
253}
254
255// -- Channel mode types --------------------------------------------------------
256
257/// Channel has not yet been configured.
258pub struct Unconfigured;
259/// Channel configured as an analog input.
260pub struct AnalogIn;
261/// Channel configured as a digital input (GPIO).
262pub struct DigitalIn;
263/// Channel configured as a digital output (GPIO). `DRIVE` is [`PushPull`] or [`OpenDrain`].
264pub struct DigitalOut<DRIVE>(core::marker::PhantomData<DRIVE>);
265/// Open-drain drive mode for [`DigitalOut`].
266pub struct OpenDrain;
267/// Push-pull drive mode for [`DigitalOut`].
268pub struct PushPull;
269
270/// Implemented by every channel typestate, exposing at compile time whether a
271/// channel is an analog input.
272///
273/// This is what lets [`Driver::ANALOG_CHANNEL_MASK`] be an associated constant:
274/// the set of channels to put in an auto-sequence is already encoded in the
275/// driver's type, so it costs nothing at runtime and cannot disagree with how
276/// the channels were actually configured.
277pub trait ChannelMode: sealed::ChannelMode {
278    /// Whether this channel takes part in ADC conversions.
279    const IS_ANALOG: bool;
280}
281
282impl sealed::ChannelMode for Unconfigured {}
283impl ChannelMode for Unconfigured {
284    const IS_ANALOG: bool = false;
285}
286impl sealed::ChannelMode for AnalogIn {}
287impl ChannelMode for AnalogIn {
288    const IS_ANALOG: bool = true;
289}
290impl sealed::ChannelMode for DigitalIn {}
291impl ChannelMode for DigitalIn {
292    const IS_ANALOG: bool = false;
293}
294impl<DRIVE> sealed::ChannelMode for DigitalOut<DRIVE> {}
295impl<DRIVE> ChannelMode for DigitalOut<DRIVE> {
296    const IS_ANALOG: bool = false;
297}
298
299// -- Driver struct -------------------------------------------------------------
300
301/// Core driver generic over bus interface (`IF`), chip capability tier (`CHIP`),
302/// and the typestate of each of the 8 channels (`C0`-`C7`).
303///
304/// Use the part-number type aliases (`Ads7138<I2C>`, `Ads7038<SPI>`, etc.)
305/// rather than constructing this type directly.
306pub struct Driver<
307    IF,
308    CHIP,
309    C0 = Unconfigured,
310    C1 = Unconfigured,
311    C2 = Unconfigured,
312    C3 = Unconfigured,
313    C4 = Unconfigured,
314    C5 = Unconfigured,
315    C6 = Unconfigured,
316    C7 = Unconfigured,
317> {
318    pub device: Device<IF>,
319    _chip: core::marker::PhantomData<CHIP>,
320    // clippy::type_complexity fires on the eight-typestate tuple. Factoring it
321    // behind an alias would satisfy the lint without telling a reader anything
322    // the tuple doesn't already say — the arity *is* the meaning here, one
323    // parameter per channel.
324    #[allow(clippy::type_complexity)]
325    _channels: core::marker::PhantomData<(C0, C1, C2, C3, C4, C5, C6, C7)>,
326}
327
328impl<BUS: I2c, CHIP: Chip> Driver<I2cInterface<BUS>, CHIP> {
329    /// Create a new I2C driver. All channels start as `Unconfigured`.
330    pub fn new(i2c: BUS, addr: Address) -> Self {
331        Self {
332            device: Device::new(I2cInterface { i2c, addr }),
333            _chip: core::marker::PhantomData,
334            _channels: core::marker::PhantomData,
335        }
336    }
337}
338
339impl<SPI: SpiDevice, CHIP: Chip> Driver<SpiInterface<SPI>, CHIP> {
340    /// Create a new SPI driver. All channels start as `Unconfigured`.
341    pub fn new(spi: SPI) -> Self {
342        Self {
343            device: Device::new(SpiInterface { spi }),
344            _chip: core::marker::PhantomData,
345            _channels: core::marker::PhantomData,
346        }
347    }
348}
349
350// -- Batch channel configuration -----------------------------------------------
351
352/// Builder for batch channel configuration, returned by [`Driver::configure`].
353///
354/// Each `chN_as_*` call only updates local state (it's sync and infallible, no
355/// bus access happens until [`Self::apply`]). `apply` then commits every
356/// accumulated change with exactly one write per touched register (`PIN_CFG`,
357/// `GPIO_CFG`, `GPO_DRIVE_CFG`), regardless of how many channels were staged.
358///
359/// ```ignore
360/// let mut adc = adc
361///     .configure()
362///     .ch0_as_analog()
363///     .ch2_as_analog()
364///     .ch4_as_digital_out_push_pull()
365///     .apply()
366///     .await?;
367/// ```
368#[must_use = "staged channel configuration does nothing until `.apply()` is called"]
369pub struct ConfigureChannels<
370    IF,
371    CHIP,
372    C0 = Unconfigured,
373    C1 = Unconfigured,
374    C2 = Unconfigured,
375    C3 = Unconfigured,
376    C4 = Unconfigured,
377    C5 = Unconfigured,
378    C6 = Unconfigured,
379    C7 = Unconfigured,
380> {
381    device: Device<IF>,
382    pin_cfg_value: u8,
383    pin_cfg_mask: u8,
384    gpio_cfg_value: u8,
385    gpio_cfg_mask: u8,
386    gpo_drive_value: u8,
387    gpo_drive_mask: u8,
388    _chip: core::marker::PhantomData<CHIP>,
389    // clippy::type_complexity fires on the eight-typestate tuple. Factoring it
390    // behind an alias would satisfy the lint without telling a reader anything
391    // the tuple doesn't already say — the arity *is* the meaning here, one
392    // parameter per channel.
393    #[allow(clippy::type_complexity)]
394    _channels: core::marker::PhantomData<(C0, C1, C2, C3, C4, C5, C6, C7)>,
395}
396
397impl<IF, CHIP: Chip, C0, C1, C2, C3, C4, C5, C6, C7>
398    Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
399{
400    /// Start a batch channel-configuration builder. No bus access happens until
401    /// [`ConfigureChannels::apply`] is called on the result.
402    pub fn configure(self) -> ConfigureChannels<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7> {
403        ConfigureChannels {
404            device: self.device,
405            pin_cfg_value: 0,
406            pin_cfg_mask: 0,
407            gpio_cfg_value: 0,
408            gpio_cfg_mask: 0,
409            gpo_drive_value: 0,
410            gpo_drive_mask: 0,
411            _chip: core::marker::PhantomData,
412            _channels: core::marker::PhantomData,
413        }
414    }
415}
416
417impl<
418    IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface,
419    CHIP: Chip,
420    C0,
421    C1,
422    C2,
423    C3,
424    C4,
425    C5,
426    C6,
427    C7,
428> ConfigureChannels<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
429{
430    /// Commit all staged channel configuration, writing each touched register
431    /// (`PIN_CFG`, `GPIO_CFG`, `GPO_DRIVE_CFG`) exactly once.
432    pub async fn apply(
433        mut self,
434    ) -> Result<Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>, IF::Error> {
435        let (mask, value) = (self.pin_cfg_mask, self.pin_cfg_value);
436        if mask != 0 {
437            self.device
438                .pin_cfg()
439                .modify_async(|r| r.set_pin_cfg((r.pin_cfg() & !mask) | (value & mask)))
440                .await?;
441        }
442        let (mask, value) = (self.gpio_cfg_mask, self.gpio_cfg_value);
443        if mask != 0 {
444            self.device
445                .gpio_cfg()
446                .modify_async(|r| r.set_gpio_cfg((r.gpio_cfg() & !mask) | (value & mask)))
447                .await?;
448        }
449        let (mask, value) = (self.gpo_drive_mask, self.gpo_drive_value);
450        if mask != 0 {
451            self.device
452                .gpo_drive_cfg()
453                .modify_async(|r| r.set_gpo_drive_cfg((r.gpo_drive_cfg() & !mask) | (value & mask)))
454                .await?;
455        }
456        Ok(Driver {
457            device: self.device,
458            _chip: core::marker::PhantomData,
459            _channels: core::marker::PhantomData,
460        })
461    }
462}
463
464// -- Global methods: all chips -------------------------------------------------
465
466impl<
467    IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface,
468    CHIP: Chip,
469    C0,
470    C1,
471    C2,
472    C3,
473    C4,
474    C5,
475    C6,
476    C7,
477> Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
478{
479    /// Reset all registers to defaults. Consumes the driver and returns a fresh
480    /// instance with all channels in the `Unconfigured` state.
481    pub async fn reset(mut self) -> Result<Driver<IF, CHIP>, IF::Error> {
482        self.device
483            .general_cfg()
484            .write_with_zero_async(|r| r.set_rst(true))
485            .await?;
486        Ok(Driver {
487            device: self.device,
488            _chip: core::marker::PhantomData,
489            _channels: core::marker::PhantomData,
490        })
491    }
492
493    /// Initiate ADC offset calibration. The `cal` bit auto-clears when complete.
494    pub async fn calibrate(&mut self) -> Result<(), IF::Error> {
495        self.device
496            .general_cfg()
497            .modify_async(|r| r.set_cal(true))
498            .await?;
499        Ok(())
500    }
501
502    /// Whether the device has recorded a brown-out reset (`SYSTEM_STATUS.BOR`).
503    ///
504    /// Set on every power-up and latched until [`Self::clear_bor`] is called, so
505    /// clearing it after configuration turns it into a reliable "did this device
506    /// reset behind my back" flag.
507    ///
508    /// Worth checking periodically on any channel configured as a GPIO. A part
509    /// that browns out and recovers still acknowledges its address and still
510    /// returns plausible conversion results — but every register is back at its
511    /// reset default, so channels configured as outputs have silently reverted
512    /// to analog inputs and stopped driving. No I2C error is produced and no
513    /// conversion looks wrong; this flag is the only signal that it happened.
514    pub async fn browned_out(&mut self) -> Result<bool, IF::Error> {
515        Ok(self.device.system_status().read_async().await?.bor())
516    }
517
518    /// Clear the brown-out reset indicator (W1C).
519    pub async fn clear_bor(&mut self) -> Result<(), IF::Error> {
520        self.device
521            .system_status()
522            .write_with_zero_async(|r| r.set_bor(true))
523            .await?;
524        Ok(())
525    }
526
527    /// Set the oversampling ratio applied to every conversion.
528    pub async fn set_oversampling(&mut self, ratio: OversamplingRatio) -> Result<(), IF::Error> {
529        self.device
530            .osr_cfg()
531            .modify_async(|r| r.set_osr(ratio))
532            .await?;
533        Ok(())
534    }
535}
536
537// -- Auto-sequence conversion: all analog channels in one burst ----------------
538
539impl<IF: CanConvert, CHIP: Chip, C0, C1, C2, C3, C4, C5, C6, C7>
540    Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
541where
542    C0: ChannelMode,
543    C1: ChannelMode,
544    C2: ChannelMode,
545    C3: ChannelMode,
546    C4: ChannelMode,
547    C5: ChannelMode,
548    C6: ChannelMode,
549    C7: ChannelMode,
550{
551    /// Bitmask of the channels this driver has configured as analog inputs,
552    /// computed from the typestate at compile time.
553    pub const ANALOG_CHANNEL_MASK: u8 = (C0::IS_ANALOG as u8)
554        | (C1::IS_ANALOG as u8) << 1
555        | (C2::IS_ANALOG as u8) << 2
556        | (C3::IS_ANALOG as u8) << 3
557        | (C4::IS_ANALOG as u8) << 4
558        | (C5::IS_ANALOG as u8) << 5
559        | (C6::IS_ANALOG as u8) << 6
560        | (C7::IS_ANALOG as u8) << 7;
561
562    /// Convert every channel configured as an analog input, returning results
563    /// indexed by channel (`None` for channels that aren't analog inputs).
564    ///
565    /// Uses the device's auto-sequencer, so the whole set costs four bus
566    /// transactions regardless of how many channels are enabled, against the two
567    /// per channel that [`Driver::read_ch0`] and friends need (a `MANUAL_CH_SEL`
568    /// write plus a conversion read each). For a board where bus activity is an
569    /// RFI budget rather than a throughput concern, that difference is the point.
570    ///
571    /// The sequencer's mode is set up and torn back down around each call, so
572    /// the device is left in manual mode and the per-channel `read_chN` methods
573    /// keep working between calls, and `AUTO_SEQ_CH_SEL` is rewritten every time
574    /// rather than cached — a device that reset behind the driver's back gets
575    /// correct configuration on the next call instead of silently sequencing the
576    /// wrong set.
577    ///
578    /// # Result attribution
579    ///
580    /// Results come back in ascending channel order and are attributed on that
581    /// basis; the device does not tag them (the 4-bit channel ID that
582    /// `DATA_CFG.APPEND_STATUS` can append occupies the low bits of a 12-bit
583    /// result, so it is unavailable at any oversampling ratio above `Osr1`,
584    /// where conversions use the full 16 bits). Mis-ordering would therefore
585    /// swap readings between channels *silently*. Two things bound that risk:
586    /// the entire sequence is consumed in one transaction and the sequencer is
587    /// restarted on every call, so no misalignment can persist across calls; and
588    /// [`Self::verify_analog_sequence_order`] checks the ordering against the
589    /// device's own channel IDs, which is worth doing once at bring-up before
590    /// trusting this on hardware you haven't run it on.
591    pub async fn read_analog_sequence(&mut self) -> Result<[Option<u16>; 8], IF::Error> {
592        let mask = Self::ANALOG_CHANNEL_MASK;
593        let mut results = [None; 8];
594        if mask == 0 {
595            return Ok(results);
596        }
597
598        let count = mask.count_ones() as usize;
599        let mut buf = [0u8; 16];
600        self.run_analog_sequence(&mut buf[..count * 2]).await?;
601
602        for (slot, channel) in (0..8u8).filter(|c| mask & (1 << c) != 0).enumerate() {
603            let hi = buf[slot * 2] as u16;
604            let lo = buf[slot * 2 + 1] as u16;
605            results[channel as usize] = Some(hi << 8 | lo);
606        }
607        Ok(results)
608    }
609
610    /// Check that the auto-sequencer returns channels in the ascending order
611    /// [`Self::read_analog_sequence`] assumes.
612    ///
613    /// Run once at bring-up, not periodically: it costs six bus transactions and
614    /// briefly changes `OSR_CFG` and `DATA_CFG`, both of which are restored
615    /// before returning. It works by dropping to `Osr1` — the one ratio that
616    /// leaves the low four bits of a conversion free — and enabling
617    /// `DATA_CFG.APPEND_STATUS = ChannelId`, so the device labels each result
618    /// with the channel it came from, then confirming those labels match the
619    /// enabled channels in ascending order.
620    ///
621    /// `Ok(false)` means the ordering assumption does not hold on this part and
622    /// [`Self::read_analog_sequence`] would mis-attribute readings; fall back to
623    /// the per-channel `read_chN` methods.
624    pub async fn verify_analog_sequence_order(&mut self) -> Result<bool, IF::Error> {
625        let mask = Self::ANALOG_CHANNEL_MASK;
626        if mask == 0 {
627            return Ok(true);
628        }
629        let count = mask.count_ones() as usize;
630
631        let saved_osr = self.device.osr_cfg().read_async().await?.osr();
632        self.device
633            .osr_cfg()
634            .modify_async(|r| r.set_osr(OversamplingRatio::Osr1))
635            .await?;
636        self.device
637            .data_cfg()
638            .modify_async(|r| r.set_append_status(AppendStatus::ChannelId))
639            .await?;
640
641        let mut buf = [0u8; 16];
642        let sequence = self.run_analog_sequence(&mut buf[..count * 2]).await;
643
644        // Restore first, unconditionally: leaving the device at Osr1 with status
645        // bytes appended would corrupt every later reading far more quietly than
646        // whatever made the sequence fail.
647        self.device
648            .data_cfg()
649            .modify_async(|r| r.set_append_status(AppendStatus::None))
650            .await?;
651        self.device
652            .osr_cfg()
653            .modify_async(|r| r.set_osr(saved_osr))
654            .await?;
655        sequence?;
656
657        let ordered = (0..8u8)
658            .filter(|c| mask & (1 << c) != 0)
659            .enumerate()
660            .all(|(slot, channel)| buf[slot * 2 + 1] & 0x0F == channel);
661        Ok(ordered)
662    }
663
664    /// Point the sequencer at the analog channels, run one pass into `out`, and
665    /// put the device back in manual mode.
666    async fn run_analog_sequence(&mut self, out: &mut [u8]) -> Result<(), IF::Error> {
667        self.device
668            .auto_seq_ch_sel()
669            .write_async(|r| r.set_auto_seq_ch_sel(Self::ANALOG_CHANNEL_MASK))
670            .await?;
671        self.device
672            .sequence_cfg()
673            .write_async(|r| {
674                r.set_seq_mode(SeqMode::AutoSequence);
675                r.set_seq_start(true);
676            })
677            .await?;
678
679        let read = self.device.interface.read_sequence_raw(out).await;
680
681        // Always restore manual mode, even if the read failed: a device left
682        // sequencing would make the next `read_chN` return some other channel.
683        self.device
684            .sequence_cfg()
685            .write_async(|r| {
686                r.set_seq_mode(SeqMode::Manual);
687                r.set_seq_start(false);
688            })
689            .await?;
690        read
691    }
692}
693
694// -- Global methods: HasStats chips (ADS7x38, ADS7x28) ------------------------
695
696impl<
697    IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface,
698    CHIP: HasStats,
699    C0,
700    C1,
701    C2,
702    C3,
703    C4,
704    C5,
705    C6,
706    C7,
707> Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
708{
709    /// Enable the digital window comparator.
710    pub async fn enable_dwc(&mut self) -> Result<(), IF::Error> {
711        self.device
712            .general_cfg()
713            .modify_async(|r| r.set_dwc_en(true))
714            .await?;
715        Ok(())
716    }
717
718    /// Disable the digital window comparator.
719    pub async fn disable_dwc(&mut self) -> Result<(), IF::Error> {
720        self.device
721            .general_cfg()
722            .modify_async(|r| r.set_dwc_en(false))
723            .await?;
724        Ok(())
725    }
726
727    /// Configure the ALERT pin driver type and assertion logic.
728    pub async fn configure_alert_pin(
729        &mut self,
730        push_pull: bool,
731        logic: AlertLogic,
732    ) -> Result<(), IF::Error> {
733        self.device
734            .alert_pin_cfg()
735            .write_with_zero_async(|r| {
736                r.set_alert_drive(push_pull);
737                r.set_alert_logic(logic);
738            })
739            .await?;
740        Ok(())
741    }
742
743    /// Set which channels can assert the ALERT pin (bit N = 1 enables CH\[N\]).
744    pub async fn set_alert_channel_mask(&mut self, mask: u8) -> Result<(), IF::Error> {
745        self.device
746            .alert_ch_sel()
747            .write_with_zero_async(|r| r.set_alert_ch_sel(mask))
748            .await?;
749        Ok(())
750    }
751
752    /// Read the combined event flags register (bit N = OR of high and low flags for CH\[N\]).
753    pub async fn event_flags(&mut self) -> Result<u8, IF::Error> {
754        Ok(self.device.event_flag().read_async().await?.event_flag())
755    }
756
757    /// Read the high-threshold (or GPIO logic-1) event flags.
758    pub async fn event_high_flags(&mut self) -> Result<u8, IF::Error> {
759        Ok(self
760            .device
761            .event_high_flag()
762            .read_async()
763            .await?
764            .event_high_flag())
765    }
766
767    /// Read the low-threshold (or GPIO logic-0) event flags.
768    pub async fn event_low_flags(&mut self) -> Result<u8, IF::Error> {
769        Ok(self
770            .device
771            .event_low_flag()
772            .read_async()
773            .await?
774            .event_low_flag())
775    }
776
777    /// Clear high-event flags for the given channel bitmask (W1C).
778    pub async fn clear_event_high_flags(&mut self, mask: u8) -> Result<(), IF::Error> {
779        self.device
780            .event_high_flag()
781            .write_with_zero_async(|r| r.set_event_high_flag(mask))
782            .await?;
783        Ok(())
784    }
785
786    /// Clear low-event flags for the given channel bitmask (W1C).
787    pub async fn clear_event_low_flags(&mut self, mask: u8) -> Result<(), IF::Error> {
788        self.device
789            .event_low_flag()
790            .write_with_zero_async(|r| r.set_event_low_flag(mask))
791            .await?;
792        Ok(())
793    }
794}
795
796// -- Global methods: HasRmsZcd chips (ADS7x28) --------------------------------
797
798impl<
799    IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface,
800    CHIP: HasRmsZcd,
801    C0,
802    C1,
803    C2,
804    C3,
805    C4,
806    C5,
807    C6,
808    C7,
809> Driver<IF, CHIP, C0, C1, C2, C3, C4, C5, C6, C7>
810{
811    /// Configure the RMS computation module.
812    ///
813    /// `channel` selects which AIN is measured; `dc_sub` subtracts the DC
814    /// component before computing; `samples` sets the accumulation window.
815    /// Call `enable_dwc()` (which also enables the statistics module) before
816    /// reading results.
817    pub async fn configure_rms(
818        &mut self,
819        channel: RmsChannelId,
820        dc_sub: bool,
821        samples: RmsSampleCount,
822    ) -> Result<(), IF::Error> {
823        self.device
824            .rms_cfg()
825            .write_with_zero_async(|r| {
826                r.set_rms_chid(channel);
827                r.set_rms_dc_sub(dc_sub);
828                r.set_rms_samples(samples);
829            })
830            .await?;
831        Ok(())
832    }
833
834    /// Read the 16-bit RMS result.
835    pub async fn read_rms(&mut self) -> Result<u16, IF::Error> {
836        let lsb = self.device.rms_lsb().read_async().await?.value();
837        let msb = self.device.rms_msb().read_async().await?.value();
838        Ok(((msb as u16) << 8) | lsb as u16)
839    }
840
841    /// Configure the zero-crossing detection blanking time.
842    ///
843    /// `multiplier_8x`: false = 1x blanking, true = 8x blanking.
844    /// `blanking`: 7-bit blanking count value.
845    pub async fn configure_zcd_blanking(
846        &mut self,
847        multiplier_8x: bool,
848        blanking: u8,
849    ) -> Result<(), IF::Error> {
850        self.device
851            .zcd_blanking_cfg()
852            .write_with_zero_async(|r| {
853                r.set_mult_en(multiplier_8x);
854                r.set_zcd_blanking(blanking & 0x7F);
855            })
856            .await?;
857        Ok(())
858    }
859
860    /// Set the GPO value driven on ZCD edge detection for channels 0-3.
861    pub async fn set_zcd_gpo_ch0_ch3(
862        &mut self,
863        ch0: ZcdGpoValue,
864        ch1: ZcdGpoValue,
865        ch2: ZcdGpoValue,
866        ch3: ZcdGpoValue,
867    ) -> Result<(), IF::Error> {
868        self.device
869            .gpo_value_zcd_cfg_ch_0_ch_3()
870            .write_with_zero_async(|r| {
871                r.set_ch_0(ch0);
872                r.set_ch_1(ch1);
873                r.set_ch_2(ch2);
874                r.set_ch_3(ch3);
875            })
876            .await?;
877        Ok(())
878    }
879
880    /// Set the GPO value driven on ZCD edge detection for channels 4-7.
881    pub async fn set_zcd_gpo_ch4_ch7(
882        &mut self,
883        ch4: ZcdGpoValue,
884        ch5: ZcdGpoValue,
885        ch6: ZcdGpoValue,
886        ch7: ZcdGpoValue,
887    ) -> Result<(), IF::Error> {
888        self.device
889            .gpo_value_zcd_cfg_ch_4_ch_7()
890            .write_with_zero_async(|r| {
891                r.set_ch_4(ch4);
892                r.set_ch_5(ch5);
893                r.set_ch_6(ch6);
894                r.set_ch_7(ch7);
895            })
896            .await?;
897        Ok(())
898    }
899
900    /// Set which GPO outputs are updated on zero-crossing detection (bit N = 1 enables GPO\[N\]).
901    pub async fn set_zcd_gpo_update_mask(&mut self, mask: u8) -> Result<(), IF::Error> {
902        self.device
903            .gpo_zcd_update_en()
904            .write_with_zero_async(|r| r.set_gpo_zcd_update_en(mask))
905            .await?;
906        Ok(())
907    }
908}
909
910// -- Per-channel typestate impl ------------------------------------------------
911
912/// Generates configure/read/write impls for one channel.
913///
914/// Arguments:
915///   $n:    channel index literal (0-7)
916///   $pre:  channel type params that come *before* channel $n in the struct
917///   $post: channel type params that come *after* channel $n in the struct
918macro_rules! impl_channel {
919    ($n:literal, ($($pre:ident),*), ($($post:ident),*)) => {
920        pastey::paste! {
921            // -- configure (from any current mode, any chip): pure bit twiddling, --
922            // -- no bus access; staged into the ConfigureChannels builder ----------
923
924            impl<IF, CHIP: Chip, [<C $n>] $(, $pre)* $(, $post)*>
925                ConfigureChannels<IF, CHIP, $($pre,)* [<C $n>], $($post,)*>
926            {
927                #[doc = concat!("Stage channel ", stringify!($n), " as an analog input.")]
928                pub fn [<ch $n _as_analog>](mut self)
929                    -> ConfigureChannels<IF, CHIP, $($pre,)* AnalogIn, $($post,)*>
930                {
931                    self.pin_cfg_mask |= 1u8 << $n;
932                    self.pin_cfg_value &= !(1u8 << $n);
933                    ConfigureChannels {
934                        device: self.device,
935                        pin_cfg_value: self.pin_cfg_value,
936                        pin_cfg_mask: self.pin_cfg_mask,
937                        gpio_cfg_value: self.gpio_cfg_value,
938                        gpio_cfg_mask: self.gpio_cfg_mask,
939                        gpo_drive_value: self.gpo_drive_value,
940                        gpo_drive_mask: self.gpo_drive_mask,
941                        _chip: core::marker::PhantomData,
942                        _channels: core::marker::PhantomData,
943                    }
944                }
945
946                #[doc = concat!("Stage channel ", stringify!($n), " as a digital input (GPIO).")]
947                pub fn [<ch $n _as_digital_in>](mut self)
948                    -> ConfigureChannels<IF, CHIP, $($pre,)* DigitalIn, $($post,)*>
949                {
950                    self.pin_cfg_mask |= 1u8 << $n;
951                    self.pin_cfg_value |= 1u8 << $n;
952                    self.gpio_cfg_mask |= 1u8 << $n;
953                    self.gpio_cfg_value &= !(1u8 << $n);
954                    ConfigureChannels {
955                        device: self.device,
956                        pin_cfg_value: self.pin_cfg_value,
957                        pin_cfg_mask: self.pin_cfg_mask,
958                        gpio_cfg_value: self.gpio_cfg_value,
959                        gpio_cfg_mask: self.gpio_cfg_mask,
960                        gpo_drive_value: self.gpo_drive_value,
961                        gpo_drive_mask: self.gpo_drive_mask,
962                        _chip: core::marker::PhantomData,
963                        _channels: core::marker::PhantomData,
964                    }
965                }
966
967                #[doc = concat!("Stage channel ", stringify!($n), " as a push-pull digital output (GPIO).")]
968                pub fn [<ch $n _as_digital_out_push_pull>](mut self)
969                    -> ConfigureChannels<IF, CHIP, $($pre,)* DigitalOut<PushPull>, $($post,)*>
970                {
971                    self.pin_cfg_mask |= 1u8 << $n;
972                    self.pin_cfg_value |= 1u8 << $n;
973                    self.gpio_cfg_mask |= 1u8 << $n;
974                    self.gpio_cfg_value |= 1u8 << $n;
975                    self.gpo_drive_mask |= 1u8 << $n;
976                    self.gpo_drive_value |= 1u8 << $n;
977                    ConfigureChannels {
978                        device: self.device,
979                        pin_cfg_value: self.pin_cfg_value,
980                        pin_cfg_mask: self.pin_cfg_mask,
981                        gpio_cfg_value: self.gpio_cfg_value,
982                        gpio_cfg_mask: self.gpio_cfg_mask,
983                        gpo_drive_value: self.gpo_drive_value,
984                        gpo_drive_mask: self.gpo_drive_mask,
985                        _chip: core::marker::PhantomData,
986                        _channels: core::marker::PhantomData,
987                    }
988                }
989
990                #[doc = concat!("Stage channel ", stringify!($n), " as an open-drain digital output (GPIO).")]
991                pub fn [<ch $n _as_digital_out_open_drain>](mut self)
992                    -> ConfigureChannels<IF, CHIP, $($pre,)* DigitalOut<OpenDrain>, $($post,)*>
993                {
994                    self.pin_cfg_mask |= 1u8 << $n;
995                    self.pin_cfg_value |= 1u8 << $n;
996                    self.gpio_cfg_mask |= 1u8 << $n;
997                    self.gpio_cfg_value |= 1u8 << $n;
998                    self.gpo_drive_mask |= 1u8 << $n;
999                    self.gpo_drive_value &= !(1u8 << $n);
1000                    ConfigureChannels {
1001                        device: self.device,
1002                        pin_cfg_value: self.pin_cfg_value,
1003                        pin_cfg_mask: self.pin_cfg_mask,
1004                        gpio_cfg_value: self.gpio_cfg_value,
1005                        gpio_cfg_mask: self.gpio_cfg_mask,
1006                        gpo_drive_value: self.gpo_drive_value,
1007                        gpo_drive_mask: self.gpo_drive_mask,
1008                        _chip: core::marker::PhantomData,
1009                        _channels: core::marker::PhantomData,
1010                    }
1011                }
1012            }
1013
1014            // -- AnalogIn: SCL-stretch (I2C) / on-the-fly (SPI) read ------
1015            //
1016            // Available on all chips. For I2C, the device stretches SCL during
1017            // conversion. For SPI, uses on-the-fly mode (section 7.4.3), no latency.
1018            //
1019            // Returns the raw 16-bit MSB-aligned ADC word:
1020            //   OSR = 0: 12-bit result in bits [15:4]; bits [3:0] = 0.
1021            //   OSR > 0: full 16-bit averaged result in bits [15:0].
1022
1023            impl<IF: CanConvert, CHIP: Chip $(, $pre)* $(, $post)*>
1024                Driver<IF, CHIP, $($pre,)* AnalogIn, $($post,)*>
1025            {
1026                pub async fn [<read_ch $n>](&mut self) -> Result<u16, IF::Error> {
1027                    self.device.interface.read_conversion_raw($n).await
1028                }
1029            }
1030
1031            // -- AnalogIn: polled read + thresholds (HasStats chips only) --
1032
1033            impl<IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface, CHIP: HasStats $(, $pre)* $(, $post)*>
1034                Driver<IF, CHIP, $($pre,)* AnalogIn, $($post,)*>
1035            {
1036                #[doc = concat!("Trigger a conversion on channel ", stringify!($n), " without SCL stretching and")]
1037                /// return the raw 16-bit MSB-aligned ADC word.
1038                ///
1039                /// Enables STATS_EN, triggers the conversion via CNVST, polls
1040                #[doc = concat!("OSR_DONE, then reads the result from the RECENT_CH", stringify!($n), " registers.")]
1041                ///
1042                /// Returns the raw 16-bit MSB-aligned ADC word:
1043                ///   OSR = 0: 12-bit result in bits \[15:4\]; bits \[3:0\] = 0.
1044                ///   OSR > 0: full 16-bit averaged result in bits \[15:0\].
1045                pub async fn [<read_ch $n _polled>](&mut self) -> Result<u16, IF::Error> {
1046                    self.device.general_cfg().modify_async(|r| r.set_stats_en(true)).await?;
1047                    self.device.manual_ch_sel().write_async(|r| {
1048                        r.set_manual_chid(ChannelId::[<Ain $n>])
1049                    }).await?;
1050                    self.device.general_cfg().modify_async(|r| r.set_cnvst(true)).await?;
1051                    loop {
1052                        if self.device.system_status().read_async().await?.osr_done() {
1053                            break;
1054                        }
1055                    }
1056                    self.device.system_status().write_with_zero_async(|r| {
1057                        r.set_osr_done(true)
1058                    }).await?;
1059                    let lsb = self.device.recent_ch_lsb().read_at_async($n).await?.value();
1060                    let msb = self.device.recent_ch_msb().read_at_async($n).await?.value();
1061                    Ok(((msb as u16) << 8) | lsb as u16)
1062                }
1063
1064                #[doc = concat!("Set the high and low alert thresholds for channel ", stringify!($n), " (12-bit, 0-4095).")]
1065                pub async fn [<set_ch $n _thresholds>](
1066                    &mut self,
1067                    high: u16,
1068                    low: u16,
1069                ) -> Result<(), IF::Error> {
1070                    self.device
1071                        .high_th_ch()
1072                        .write_with_zero_at_async($n, |r| r.set_high_threshold_msb((high >> 4) as u8))
1073                        .await?;
1074                    self.device
1075                        .hysteresis_ch()
1076                        .modify_at_async($n, |r| r.set_high_threshold_lsb((high & 0xF) as u8))
1077                        .await?;
1078                    self.device
1079                        .low_th_ch()
1080                        .write_with_zero_at_async($n, |r| r.set_low_threshold_msb((low >> 4) as u8))
1081                        .await?;
1082                    self.device
1083                        .event_count_ch()
1084                        .modify_at_async($n, |r| r.set_low_threshold_lsb((low & 0xF) as u8))
1085                        .await?;
1086                    Ok(())
1087                }
1088
1089                #[doc = concat!("Set the hysteresis for channel ", stringify!($n), " (4-bit; effective value = `hyst << 3` LSBs).")]
1090                pub async fn [<set_ch $n _hysteresis>](
1091                    &mut self,
1092                    hyst: u8,
1093                ) -> Result<(), IF::Error> {
1094                    self.device
1095                        .hysteresis_ch()
1096                        .modify_at_async($n, |r| r.set_hysteresis(hyst & 0xF))
1097                        .await?;
1098                    Ok(())
1099                }
1100
1101                #[doc = concat!("Set the event count for channel ", stringify!($n), " (4-bit; alert fires after `count + 1`")]
1102                /// consecutive threshold violations).
1103                pub async fn [<set_ch $n _event_count>](
1104                    &mut self,
1105                    count: u8,
1106                ) -> Result<(), IF::Error> {
1107                    self.device
1108                        .event_count_ch()
1109                        .modify_at_async($n, |r| r.set_event_count(count & 0xF))
1110                        .await?;
1111                    Ok(())
1112                }
1113            }
1114
1115            // -- DigitalIn: read (all chips) -------------------------------
1116
1117            impl<IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface, CHIP: Chip $(, $pre)* $(, $post)*>
1118                Driver<IF, CHIP, $($pre,)* DigitalIn, $($post,)*>
1119            {
1120                pub async fn [<is_ch $n _high>](&mut self) -> Result<bool, IF::Error> {
1121                    Ok(self.device.gpi_value().read_async().await?.gpi_value() & (1u8 << $n) != 0)
1122                }
1123            }
1124
1125            // -- DigitalOut: write (all chips) -----------------------------
1126
1127            impl<IF: RegisterInterfaceBase<AddressType = u8> + AsyncRegisterInterface, CHIP: Chip, D $(, $pre)* $(, $post)*>
1128                Driver<IF, CHIP, $($pre,)* DigitalOut<D>, $($post,)*>
1129            {
1130                pub async fn [<write_ch $n>](&mut self, high: bool) -> Result<(), IF::Error> {
1131                    self.device.gpo_value().modify_async(|r| {
1132                        let v = r.gpo_value();
1133                        r.set_gpo_value(if high { v | (1u8 << $n) } else { v & !(1u8 << $n) })
1134                    }).await?;
1135                    Ok(())
1136                }
1137            }
1138        }
1139    }
1140}
1141
1142impl_channel!(0, (), (C1, C2, C3, C4, C5, C6, C7));
1143impl_channel!(1, (C0), (C2, C3, C4, C5, C6, C7));
1144impl_channel!(2, (C0, C1), (C3, C4, C5, C6, C7));
1145impl_channel!(3, (C0, C1, C2), (C4, C5, C6, C7));
1146impl_channel!(4, (C0, C1, C2, C3), (C5, C6, C7));
1147impl_channel!(5, (C0, C1, C2, C3, C4), (C6, C7));
1148impl_channel!(6, (C0, C1, C2, C3, C4, C5), (C7));
1149impl_channel!(7, (C0, C1, C2, C3, C4, C5, C6), ());
1150
1151// -- Per-part-number type aliases ----------------------------------------------
1152
1153macro_rules! chip_alias {
1154    ($bus:ident : $(#[$attr:meta])* $name:ident, $chip:ty) => {
1155        pastey::paste! {
1156            $(#[$attr])*
1157            pub type $name<
1158                BUS,
1159                C0 = Unconfigured,
1160                C1 = Unconfigured,
1161                C2 = Unconfigured,
1162                C3 = Unconfigured,
1163                C4 = Unconfigured,
1164                C5 = Unconfigured,
1165                C6 = Unconfigured,
1166                C7 = Unconfigured,
1167            > = Driver<[<$bus:camel Interface>]<BUS>, $chip, C0, C1, C2, C3, C4, C5, C6, C7>;
1168        }
1169    };
1170}
1171
1172chip_alias!(i2c: Tla2528, Tla252x);
1173chip_alias!(spi: Tla2518, Tla252x);
1174chip_alias!(i2c: Ads7138, Ads7x38);
1175chip_alias!(spi: Ads7038, Ads7x38);
1176chip_alias!(spi:
1177    /// ADS7038H is a higher-throughput (1.5 MSPS vs 1 MSPS) SPI variant of the ADS7038.
1178    /// The register map and feature set are identical; the speed difference is a hardware
1179    /// characteristic with no register-level impact.
1180    Ads7038H,
1181    Ads7x38
1182);
1183chip_alias!(i2c: Ads7128, Ads7x28);
1184chip_alias!(spi: Ads7028, Ads7x28);