Skip to main content

Crate ti_adc_expander

Crate ti_adc_expander 

Source
Expand description

§ti-adc-expander

Crates.io docs.rs

An async Rust driver for the TI family of 12-bit, 8-channel ADC + GPIO expander chips:

PartInterfaceMax rateChip typeDWC / Alerts / StatsRMSZCD
TLA2518SPI1 MSPSTla252x
TLA2528I2C140 kSPSTla252x
ADS7038SPI1 MSPSAds7x38x
ADS7038HSPI1.5 MSPSAds7x38x
ADS7138I2C140 kSPSAds7x38x
ADS7028SPI1 MSPSAds7x28xxx
ADS7128I2C140 kSPSAds7x28xxx

All chips are type-aliased (Ads7138<I2C>, Ads7038<SPI>, Tla2528<I2C>, etc.) over a common Driver<IF, CHIP, C0..C7> struct. Features unavailable on a given chip are gated at compile time via trait bounds. For example, calling read_ch0_polled() on a Tla252x is a type error.

Built on embedded-hal-async and device-driver. All methods return the bus error type directly.

Note: SPI support is implemented based on the datasheet but has not been validated on hardware. Only the I2C variants (TLA2528, ADS7138, ADS7128) have been tested. Bug reports and PRs for SPI are welcome.

§Features

  • Async-only, no_std compatible
  • I2C and SPI support via embedded-hal-async
  • Compile-time chip capability gating via sealed trait hierarchy
  • Typestate-enforced channel configuration, analog / digital-in / digital-out modes are verified at compile time
  • Three analog read strategies:
    • Direct read (read_chN): I2C uses SCL stretching; SPI uses on-the-fly mode (channel encoded in first 5 SDI bits, zero conversion latency)
    • Polled read (read_chN_polled, ADS7x38 / ADS7x28 only): triggers via CNVST, polls OSR_DONE, reads from RECENT_CHx statistics registers, no clock stretching, works on both I2C and SPI
    • Sequenced read (read_analog_sequence): every channel typed as an analog input in one auto-sequencer pass, four bus transactions total instead of two per channel
  • Both read methods return a raw 16-bit MSB-aligned 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]
  • Brown-out detection (browned_out): a device that resets and recovers still answers normally, so SYSTEM_STATUS.BOR is the only signal that its configuration is gone
  • Full register access via the device field for anything not covered by the API
  • Optional defmt support via the defmt feature

§Cargo.toml

[dependencies]
ti-adc-expander = "0.2"

To enable defmt:

ti-adc-expander = { version = "0.2", features = ["defmt"] }

§Chip capability tiers

Tla252x  (TLA2518 / TLA2528)
|  ADC reads (SCL-stretch), GPIO, oversampling, sequencing
|
+-- Ads7x38  (ADS7038 / ADS7138)          [+ HasStats]
    |  Polled ADC reads, digital window comparator,
    |  per-channel alert thresholds, min/max/recent statistics,
    |  ALERT pin, GPO trigger on events
    |
    +-- Ads7x28  (ADS7028 / ADS7128)      [+ HasRmsZcd]
           RMS computation, zero-crossing detection,
           ZCD-linked GPO output control

§I2C address

The device address is set by resistors on the ADDR pin (I2C parts only):

VariantAddressR1R2
X100x10DNPDNP
X110x11DNP11 kOhm
X120x12DNP33 kOhm
X130x13DNP100 kOhm
X140x14100 kOhmDNP
X150x1533 kOhmDNP
X160x1611 kOhmDNP
X170x170 OhmDNP

§Quick start

§I2C

// Create the driver: all channels start as `Unconfigured`
let mut adc = Ads7138::new(i2c, Address::X10);

// Optional: clear the power-on brown-out flag and set oversampling
adc.clear_bor().await?;
adc.set_oversampling(OversamplingRatio::Osr16).await?;

// Configure channels: staging is sync (no bus access); `apply()` commits
// everything with one write per touched register and returns the driver
// with the updated channel types baked into the signature
let mut adc = adc
    .configure()
    .ch0_as_analog()
    .ch1_as_analog()
    .ch2_as_digital_in()
    .ch3_as_digital_out_push_pull()
    .apply()
    .await?;

// Read analog via SCL stretching (all chips)
let raw: u16 = adc.read_ch0().await?;    // 16-bit MSB-aligned; >> 4 for 12-bit

// Read without SCL stretching (ADS7x38 / ADS7x28 only)
let raw: u16 = adc.read_ch0_polled().await?;

// Digital I/O
let high: bool = adc.is_ch2_high().await?;
adc.write_ch3(true).await?;

§SPI

// SPI driver, no address needed
let mut adc = Ads7038::new(spi);

let mut adc = adc.configure().ch0_as_analog().ch1_as_analog().apply().await?;

// Read analog via on-the-fly mode (all SPI chips)
let raw: u16 = adc.read_ch0().await?;    // 16-bit MSB-aligned; >> 4 for 12-bit

// Read via statistics registers (ADS7x38 / ADS7x28 only)
let raw: u16 = adc.read_ch0_polled().await?;

§Analog reads

Both methods return a raw 16-bit MSB-aligned word. With OSR = 0 (no averaging) the 12-bit result occupies bits [15:4] and bits [3:0] are zero, shift right by 4 to get a value in 0-4095. With OSR > 0 (averaging enabled) the full 16-bit result occupies bits [15:0].

read_chN (all chips):

  • I2C: bare read causes the device to stretch SCL while converting (~1.17 us at 1 MHz). Not supported by all I2C host controllers.
  • SPI: on-the-fly mode, channel ID is encoded in the first 5 SDI bits of a 2-byte frame. The ADC samples on the CS edge; zero conversion latency.

read_chN_polled (ADS7x38 / ADS7x28 only): Enables STATS_EN, triggers conversion via CNVST, spins until OSR_DONE, then reads from the RECENT_CHx statistics registers. Works on both I2C and SPI. Not available on TLA252x, which lacks the statistics register block.

read_analog_sequence (all chips): converts every channel typed as an analog input in a single pass of the device’s auto-sequencer, returning results indexed by channel. Four bus transactions for the whole set, against two per channel for read_chN — worth having where bus activity is itself a cost, such as a board where each transaction is a burst of digital edges next to sensitive analog circuitry. The set of channels comes from ANALOG_CHANNEL_MASK, derived from the driver’s typestate, so it cannot disagree with how the channels were configured. The sequencer’s mode is set up and torn down around each call, so read_chN keeps working in between.

Results are returned in ascending channel order and attributed on that basis; the device cannot tag them, because the 4-bit channel ID that DATA_CFG.APPEND_STATUS appends occupies the low bits of a 12-bit result and so is unavailable at any OSR above Osr1. verify_analog_sequence_order checks that assumption against the device’s own channel IDs — it drops to Osr1, enables the channel-ID append, runs one sequence, and restores both registers. Run it once at bring-up; Ok(false) means fall back to the per-channel methods.

let mut adc = Ads7138::new(i2c, Address::X10)
    .configure()
    .ch0_as_analog()
    .ch3_as_digital_out_push_pull()
    .ch7_as_analog()
    .apply()
    .await?;
adc.set_oversampling(OversamplingRatio::Osr4).await?;

// Confirm the sequencer's ordering once, before relying on it.
let sequenced = adc.verify_analog_sequence_order().await?;

let results = if sequenced {
    adc.read_analog_sequence().await?
} else {
    let mut r = [None; 8];
    r[0] = Some(adc.read_ch0().await?);
    r[7] = Some(adc.read_ch7().await?);
    r
};

// Only the analog channels are populated; CH3 is a GPIO output.
assert!(results[3].is_none());

§Alert thresholds (ADS7x38 / ADS7x28)

// Set 12-bit high/low thresholds for channel 0
adc.set_ch0_thresholds(3000, 500).await?;
adc.set_ch0_hysteresis(4).await?;       // effective = 4 << 3 LSBs
adc.set_ch0_event_count(2).await?;      // alert fires after 3 consecutive violations

// Configure the ALERT pin (open-drain, active-low)
adc.set_alert_channel_mask(0b0000_0001).await?;
adc.configure_alert_pin(false, AlertLogic::ActiveLow).await?;

// Read and clear flags
let highs = adc.event_high_flags().await?;
adc.clear_event_high_flags(highs).await?;

§RMS and ZCD (ADS7x28 only)

let mut adc = Ads7128::new(i2c, Address::X10);

// Enable statistics (required for RMS)
adc.enable_dwc().await?;

// Configure and read RMS on channel 0
adc.configure_rms(RmsChannelId::Ain0, true, RmsSampleCount::Samples4096).await?;
let rms: u16 = adc.read_rms().await?;

// Zero-crossing detection
adc.configure_zcd_blanking(false, 10).await?;
adc.set_zcd_gpo_ch0_ch3(
    ZcdGpoValue::Rise1Fall0,
    ZcdGpoValue::Rise0Fall0,
    ZcdGpoValue::Rise0Fall0,
    ZcdGpoValue::Rise0Fall0,
).await?;
adc.set_zcd_gpo_update_mask(0b0000_0001).await?;

§Reset

reset() issues a soft reset and returns a fresh driver with all channels back to Unconfigured, preserving the chip type:

let adc = adc.reset().await?;
// adc is now Ads7138<I2C>, all channel type params are Unconfigured

§Direct register access

The device field exposes the full register map for anything not covered by the high-level API:

adc.device.opmode_cfg().modify_async(|r| {
    r.set_conv_mode(ConvMode::Autonomous)
}).await?;

adc.device.sequence_cfg().modify_async(|r| {
    r.set_seq_mode(SeqMode::AutoSequence);
    r.set_seq_start(true);
}).await?;

adc.device.auto_seq_ch_sel().write_with_zero_async(|r| {
    r.set_auto_seq_ch_sel(0x0F)
}).await?;

§License

Licensed under either of Apache License 2.0 or MIT License at your option.

Structs§

Ads7x28
ADS7028 (SPI) / ADS7128 (I2C): full feature set, adds RMS computation and zero-crossing detection on top of all ADS7x38 capabilities.
Ads7x38
ADS7038 (SPI) / ADS7138 (I2C): adds digital window comparator, per-channel alert thresholds, statistics (min/max/recent) registers, and GPO trigger.
AlertChSel
AlertFuncSel
AlertPinCfg
AnalogIn
Channel configured as an analog input.
AutoSeqChSel
ConfigureChannels
Builder for batch channel configuration, returned by Driver::configure.
DataCfg
Device
Root block of the Device driver
DigitalIn
Channel configured as a digital input (GPIO).
DigitalOut
Channel configured as a digital output (GPIO). DRIVE is PushPull or OpenDrain.
Driver
Core driver generic over bus interface (IF), chip capability tier (CHIP), and the typestate of each of the 8 channels (C0-C7).
EventCountCh
EventFlag
EventHighFlag
EventLowFlag
EventRgn
GeneralCfg
GpiValue
GpioCfg
GpoDriveCfg
GpoTrigEventSel
GpoTriggerCfg
GpoValue
GpoValueTrig
GpoValueZcdCfgCh0Ch3
GpoValueZcdCfgCh4Ch7
GpoZcdUpdateEn
HighThCh
HysteresisCh
I2cInterface
I2C bus interface. Used by TLA2528, ADS7138, ADS7128.
LowThCh
ManualChSel
MaxChLsb
MaxChMsb
MinChLsb
MinChMsb
OpenDrain
Open-drain drive mode for DigitalOut.
OpmodeCfg
OsrCfg
PinCfg
PushPull
Push-pull drive mode for DigitalOut.
RecentChLsb
RecentChMsb
RmsCfg
RmsLsb
RmsMsb
SequenceCfg
SpiInterface
SPI bus interface. Used by TLA2518, ADS7038, ADS7038H, ADS7028.
SystemStatus
Tla252x
TLA2518 (SPI) / TLA2528 (I2C): base feature set. Supports ADC conversion, GPIO, oversampling, and sequencing. No alert output, no statistics registers, no DWC.
Unconfigured
Channel has not yet been configured.
ZcdBlankingCfg

Enums§

Address
I2C address as set by the R1/R2 resistors on the ADDR pin. See datasheet Table 1.
AlertLogic
ALERT pin assertion behavior.
AppendStatus
Controls what is appended after the ADC output word.
ChannelId
Analog input channel selection.
ConvMode
Selects how conversions are initiated.
OversamplingRatio
Number of samples averaged per conversion result.
RmsChannelId
Analog input channel to compute RMS on.
RmsSampleCount
Number of samples accumulated for the RMS calculation.
SeqMode
Channel scanning mode for the sequencer.
ZcdGpoValue
GPO output value applied on a zero-crossing detection edge (rise/fall).

Traits§

CanConvert
Low-level trait for raw ADC output frame reads.
ChannelMode
Implemented by every channel typestate, exposing at compile time whether a channel is an analog input.
Chip
Marker trait implemented by all supported chips in this family.
HasRmsZcd
Implemented by chips with RMS computation and zero-crossing detection: ADS7x28 only.
HasStats
Implemented by chips with alert output, digital window comparator, threshold registers, and statistics (min/max/recent): ADS7x38 and ADS7x28.

Type Aliases§

Ads7028
Ads7038
Ads7128
Ads7138
Ads7038H
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.
Tla2518
Tla2528