SparkFun GM-X02B Arduino Library  v1.0.1
An Arduino library for the SparkFun Qwiic MEMS gas sensor breakouts built on the Winsen GM-x02B sensor family
Loading...
Searching...
No Matches
sfDevGMX02B Class Reference

Platform-independent driver for the SparkFun Qwiic MEMS gas sensor breakouts. More...

#include <sfDevGMX02B.h>

Inheritance diagram for sfDevGMX02B:
SfeGMX02BArd SfeGM102BArd SfeGM202BArd SfeGM302BArd SfeGM402BArd SfeGM502BArd SfeGM512BArd SfeGM602BArd SfeGM702BArd SfeGM802BArd

Public Member Functions

 sfDevGMX02B (sfe_gmx02b_sensor_t sensor)
 Construct a driver for a specific family member.
 
sfTkError_t begin (sfTkIBus *theBus=nullptr)
 Initialize the device driver with the given bus.
 
bool isConnected (void)
 Check whether the board's ADC is connected and responding.
 
bool probeADC (bool assumeUnconfigured=false)
 Check that the responding device looks like an ADC101C021.
 
bool setSensorType (sfe_gmx02b_sensor_t sensor)
 Declare which family member is installed.
 
sfe_gmx02b_sensor_t getSensorType (void)
 Get the declared sensor variant.
 
const sfe_gmx02b_part_t * getPartInfo (void)
 Get the descriptor for the current sensor variant.
 
const char * getSensorName (void)
 Get a printable name for the current sensor variant.
 
const char * getTargetGas (void)
 Get a printable target gas description for the current sensor variant.
 
uint8_t getDefaultAddress (void)
 Get the factory-default I2C address for the current sensor variant.
 
bool rsRisesWithGas (void)
 Report whether Rs rises or falls with target gas concentration.
 
float getRangeMin_ppm (void)
 Get the low end of the part's detection range.
 
float getRangeMax_ppm (void)
 Get the high end of the part's detection range.
 
float getRatedSensitivity (void)
 Get the datasheet response ratio bound for this part.
 
float getRatedConcentration_ppm (void)
 Get the concentration at which getRatedSensitivity() is specified.
 
sfTkError_t readMeasurement (void)
 Read one conversion from the ADC and cache the result.
 
uint16_t getRaw (void)
 Get the raw 10-bit ADC value from the most recent readMeasurement().
 
float getVoltage_V (void)
 Get the sensor output voltage from the most recent readMeasurement().
 
sfTkError_t getSensorResistance_Ohm (float &ohms)
 Get the sensing element resistance (Rs) from the most recent readMeasurement().
 
sfTkError_t getRatio (float &ratio)
 Get the raw Rs/R0 ratio from the most recent readMeasurement().
 
sfTkError_t getGasResponse (float &response)
 Get the direction-normalized gas response from the most recent readMeasurement().
 
bool getAlertTriggered (void)
 Get the ADC alert flag from the most recent readMeasurement().
 
void setSupplyVoltage_V (float volts)
 Set the sensing circuit supply voltage used by getVoltage_V(), voltageToCounts() and countsToVoltage_V().
 
float getSupplyVoltage_V (void)
 Get the configured sensing circuit supply voltage.
 
void setLoadResistance_Ohm (float ohms)
 Override the load resistance (RL) used by getSensorResistance_Ohm().
 
float getLoadResistance_Ohm (void)
 Get the configured load resistance.
 
uint16_t voltageToCounts (float volts)
 Convert a voltage into the equivalent 10-bit ADC counts.
 
float countsToVoltage_V (uint16_t counts)
 Convert 10-bit ADC counts into the equivalent sensor output voltage.
 
uint16_t resistanceToCounts (float ohms)
 Convert a sensor resistance into the equivalent 10-bit ADC counts.
 
sfTkError_t responseToCounts (float response, uint16_t &counts)
 Convert a gas response ratio into the equivalent 10-bit ADC counts.
 
sfTkError_t measureCleanAirResistance (float &r0, uint8_t samples=kCleanAirSamples, uint16_t sampleDelayMs=kCleanAirSampleDelayMs)
 Measure and store the clean-air sensor resistance (R0).
 
void setCleanAirResistance_Ohm (float ohms)
 Set the clean-air resistance (R0) directly.
 
float getCleanAirResistance_Ohm (void)
 Get the stored clean-air resistance (R0).
 
void setResponseCurve (float a, float b)
 Set a power-law curve that converts gas response into a concentration.
 
sfTkError_t getConcentration_ppm (float &ppm)
 Get the estimated target gas concentration.
 
bool isInRange (float ppm)
 Check whether a concentration falls inside the part's rated detection range.
 
sfTkError_t setGasAlertResponse (float response)
 Set a hardware gas threshold in gas response units.
 
sfTkError_t getGasAlert (bool &gasDetected)
 Read the hardware alert status as a single "gas detected" flag.
 
sfTkError_t setAlertLowLimit (uint16_t counts)
 Set the alert low limit (under-range threshold).
 
sfTkError_t getAlertLowLimit (uint16_t &counts)
 Get the alert low limit.
 
sfTkError_t setAlertHighLimit (uint16_t counts)
 Set the alert high limit (over-range threshold).
 
sfTkError_t getAlertHighLimit (uint16_t &counts)
 Get the alert high limit.
 
sfTkError_t setAlertHysteresis (uint16_t counts)
 Set the alert hysteresis.
 
sfTkError_t getAlertHysteresis (uint16_t &counts)
 Get the alert hysteresis.
 
sfTkError_t setAlertHysteresis_mV (float millivolts)
 Set the alert hysteresis as a sensor-output voltage band.
 
sfTkError_t getAlertHysteresis_mV (float &millivolts)
 Get the alert hysteresis as a sensor-output voltage band.
 
sfTkError_t enableAlertFlag (bool enable)
 Enable or disable the alert flag in the conversion result register.
 
sfTkError_t enableAlertPin (bool enable)
 Enable or disable the ADC's ALERT output pin.
 
sfTkError_t setAlertPinActiveHigh (bool activeHigh)
 Set the active polarity of the ALERT output pin.
 
sfTkError_t enableAlertHold (bool enable)
 Enable or disable alert hold.
 
sfTkError_t getAlertStatus (bool &underRange, bool &overRange)
 Read the raw alert status flags.
 
sfTkError_t clearAlertStatus (void)
 Clear both alert status flags.
 
sfTkError_t setCycleTime (sfe_gmx02b_cycle_time_t cycleTime)
 Set the automatic conversion cycle time (enables / disables automatic mode).
 
sfTkError_t getCycleTime (sfe_gmx02b_cycle_time_t &cycleTime)
 Get the automatic conversion cycle time.
 
sfTkError_t getPeakGasCounts (uint16_t &counts)
 Get the peak GAS conversion recorded in automatic conversion mode.
 
sfTkError_t getPeakGasVoltage_V (float &volts)
 Get the peak gas conversion as a sensor output voltage.
 
sfTkError_t clearPeakGasCounts (void)
 Reset the peak gas tracking register for this part.
 
sfTkError_t getLowestConversion (uint16_t &counts)
 Get the lowest conversion result recorded in automatic conversion mode.
 
sfTkError_t getHighestConversion (uint16_t &counts)
 Get the highest conversion result recorded in automatic conversion mode.
 
sfTkError_t clearLowestConversion (void)
 Reset the lowest conversion register (to full scale).
 
sfTkError_t clearHighestConversion (void)
 Reset the highest conversion register (to zero).
 

Protected Member Functions

sfTkError_t readRegister8 (uint8_t reg, uint8_t &value)
 Read an 8-bit register from the ADC.
 
sfTkError_t writeRegister8 (uint8_t reg, uint8_t value)
 Write an 8-bit register on the ADC.
 
sfTkError_t readRegister16 (uint8_t reg, uint16_t &value)
 Read a 16-bit register from the ADC (most significant byte first).
 
sfTkError_t writeRegister16 (uint8_t reg, uint16_t value)
 Write a 16-bit register on the ADC (most significant byte first).
 
sfTkError_t readValueRegister (uint8_t reg, uint16_t &counts)
 Read a 10-bit value register (value stored in bits 11:2).
 
sfTkError_t writeValueRegister (uint8_t reg, uint16_t counts)
 Write a 10-bit value register (value stored in bits 11:2).
 
sfTkError_t updateConfiguration (uint8_t mask, uint8_t value)
 Read-modify-write bits of the 8-bit configuration register.
 

Protected Attributes

sfTkIBus * _theBus
 Pointer to the communication bus device.
 
sfe_gmx02b_sensor_t _sensorType = GM_602B
 Declared sensor variant.
 
const sfe_gmx02b_part_t * _part = nullptr
 Descriptor for _sensorType. Never null after construction.
 
uint16_t _counts = 0
 Raw 10-bit ADC value.
 
bool _alertFlag = false
 Alert flag (bit D15) from the conversion result.
 
float _supplyVoltage = kSupplyVoltageDefault
 ADC reference / sensing loop supply (V).
 
float _loadResistance = 0.0f
 Load resistor RL (Ohm). Set from the part descriptor.
 
float _cleanAirResistance = 0.0f
 Stored clean-air sensor resistance R0 (Ohm); 0 = not set.
 
float _curveA = 0.0f
 Multiplier; 0 = no curve set.
 
float _curveB = 0.0f
 Exponent.
 

Static Protected Attributes

static const uint8_t kRegConversionResult = 0x00
 Conversion result (16-bit, read only).
 
static const uint8_t kRegAlertStatus = 0x01
 Alert status flags (8-bit).
 
static const uint8_t kRegConfiguration = 0x02
 Configuration (8-bit).
 
static const uint8_t kRegLowLimit = 0x03
 Alert low limit (16-bit).
 
static const uint8_t kRegHighLimit = 0x04
 Alert high limit (16-bit).
 
static const uint8_t kRegHysteresis = 0x05
 Alert hysteresis (16-bit).
 
static const uint8_t kRegLowestConversion = 0x06
 Lowest conversion seen (16-bit).
 
static const uint8_t kRegHighestConversion = 0x07
 Highest conversion seen (16-bit).
 
static const uint8_t kValueShift = 2
 Bit position of the 10-bit value.
 
static const uint16_t kValueMask = 0x03FF
 Mask for the 10-bit value (after shifting).
 
static const uint16_t kAlertFlagMask = 0x8000
 Alert flag (D15) in the conversion result.
 
static const uint16_t kValueReservedMask = 0xF003
 D15:D12 and D1:D0.
 
static const uint8_t kAlertStatusUnderRange = 0x01
 Under-range alert flag.
 
static const uint8_t kAlertStatusOverRange = 0x02
 Over-range alert flag.
 
static const uint8_t kConfigCycleTimeMask = 0xE0
 Cycle time field (D7:5).
 
static const uint8_t kConfigCycleTimeShift = 5
 Cycle time field bit position.
 
static const uint8_t kConfigAlertHold = 0x10
 Alert hold enable (D4).
 
static const uint8_t kConfigAlertFlagEnable = 0x08
 Conversion result alert flag enable (D3).
 
static const uint8_t kConfigAlertPinEnable = 0x04
 ALERT pin enable (D2).
 
static const uint8_t kConfigReserved = 0x02
 Reserved, reads zero (D1).
 
static const uint8_t kConfigPolarity = 0x01
 ALERT pin polarity: 1 = active high (D0).
 
static const uint16_t kAdcFullScale = 1024
 10-bit ADC full-scale count (1 LSB = VA / 1024).
 
static const uint16_t kAdcMaxCounts = 1023
 Maximum 10-bit ADC value.
 
static constexpr float kAdcFullScaleInv = 1.0f / 1024.0f
 Precomputed 1 / full scale.
 
static constexpr float kSupplyVoltageDefault = 3.3f
 Qwiic 3.3 V rail powers ADC and sensing loop.
 
static const uint8_t kCleanAirSamples = 16
 Default readings averaged for R0.
 
static const uint16_t kCleanAirSampleDelayMs = 50
 Default delay between R0 readings (ms).
 

Detailed Description

Platform-independent driver for the SparkFun Qwiic MEMS gas sensor breakouts.

This class implements register-level access to the onboard ADC101C021 via the SparkFun Toolkit bus interface, plus the divider math that turns conversions into sensor resistance and the per-part knowledge that turns resistance into a direction-normalized gas response. Most methods return a SparkFun Toolkit error code (::ksfTkErrOk on success, a negative value on error).

The typical polling flow is: begin(), then readMeasurement() followed by getRaw() / getVoltage_V() / getSensorResistance_Ohm(). For relative gas measurement, take a clean-air reference once with measureCleanAirResistance() and then read getGasResponse(). For hardware-monitored threshold alerts, set a limit with setGasAlertResponse(), enable automatic conversion mode with setCycleTime(), and check getGasAlert() (or wire up the board's ALERT pin).

Constructor & Destructor Documentation

◆ sfDevGMX02B()

sfDevGMX02B::sfDevGMX02B ( sfe_gmx02b_sensor_t sensor)
inline

Construct a driver for a specific family member.

The sensing element cannot be identified from the hardware, so declaring it here is how the driver learns the curve direction and the board's load resistance. There is no default, because the wrong part inverts the GM-102B's readings and selects the wrong load resistor.

Parameters
sensorThe sensor variant installed on the board. GM_UNKNOWN and out-of-range values are a programming error; they fall back to the GM-602B's circuit parameters (4.7 kOhm, falling Rs) so that no accessor can dereference a null descriptor.

Member Function Documentation

◆ begin()

sfTkError_t sfDevGMX02B::begin ( sfTkIBus * theBus = nullptr)

Initialize the device driver with the given bus.

Adopts the supplied bus and confirms the onboard ADC101C021 is responding.

Parameters
theBusPointer to the initialized bus object. If null, a bus set by a prior call is used.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ clearAlertStatus()

sfTkError_t sfDevGMX02B::clearAlertStatus ( void )

Clear both alert status flags.

Writing a one to each flag clears it. If the reading still violates a limit, the alert re-asserts after the next conversion.

Returns
::ksfTkErrOk on success, or an error code on failure.

◆ clearHighestConversion()

sfTkError_t sfDevGMX02B::clearHighestConversion ( void )

Reset the highest conversion register (to zero).

Returns
::ksfTkErrOk on success, or an error code on failure.

◆ clearLowestConversion()

sfTkError_t sfDevGMX02B::clearLowestConversion ( void )

Reset the lowest conversion register (to full scale).

Returns
::ksfTkErrOk on success, or an error code on failure.

◆ clearPeakGasCounts()

sfTkError_t sfDevGMX02B::clearPeakGasCounts ( void )

Reset the peak gas tracking register for this part.

Returns
::ksfTkErrOk on success, or an error code on failure.

◆ countsToVoltage_V()

float sfDevGMX02B::countsToVoltage_V ( uint16_t counts)

Convert 10-bit ADC counts into the equivalent sensor output voltage.

The inverse of voltageToCounts(): volts = counts / 1024 x supply voltage. Useful for expressing raw register values, such as the alert limits or the lowest / highest conversion registers, in volts.

Parameters
countsRaw ADC counts (0 to 1023).
Returns
Equivalent sensor output voltage in volts.

◆ enableAlertFlag()

sfTkError_t sfDevGMX02B::enableAlertFlag ( bool enable)

Enable or disable the alert flag in the conversion result register.

Parameters
enabletrue to enable the flag, false to disable it (default off).
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ enableAlertHold()

sfTkError_t sfDevGMX02B::enableAlertHold ( bool enable)

Enable or disable alert hold.

When enabled, alerts do not self-clear when the reading moves back within the limits; they persist until cleared with clearAlertStatus().

Parameters
enabletrue to hold alerts, false to allow self-clearing.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ enableAlertPin()

sfTkError_t sfDevGMX02B::enableAlertPin ( bool enable)

Enable or disable the ADC's ALERT output pin.

The ALERT pin is broken out on the board's PTH header. Per the ADC101C021 datasheet it "is an open drain data line that must be pulled to the supply (VA) with an external pull-up resistor". It is open-drain in both polarity modes, since setAlertPinActiveHigh() changes only the logic sense, not the output structure.

Warning
THE SPARKFUN BOARD DOES NOT POPULATE A PULL-UP ON ALERT. The pin floats until you provide one.
Note
An external resistor is usually unnecessary: the pin's high-impedance leakage is 1 uA max, so an MCU's internal pull-up (pinMode(pin, INPUT_PULLUP), typically 20-50 kOhm) holds it within ~50 mV of the rail. Fit a discrete 10 kOhm to 3.3 V when the MCU pin has no internal pull-up, when several boards share one alert line, or when a long trace needs faster edges. That gives 330 uA of sink current, 10 mV of droop and a ~0.2 us edge. Stay between 1 kOhm and 100 kOhm. Pulling low is not an issue: VOL is 0.4 V max at 3 mA.
The pin is not required to use the alert function. getGasAlert() reads the same condition over I2C. When the pin is disabled (the default), it stays high-impedance.
Parameters
enabletrue to enable the ALERT pin, false to disable it.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getAlertHighLimit()

sfTkError_t sfDevGMX02B::getAlertHighLimit ( uint16_t & counts)

Get the alert high limit.

Parameters
countsOutput reference that receives the threshold in raw ADC counts.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getAlertHysteresis()

sfTkError_t sfDevGMX02B::getAlertHysteresis ( uint16_t & counts)

Get the alert hysteresis.

Parameters
countsOutput reference that receives the hysteresis in raw ADC counts.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getAlertHysteresis_mV()

sfTkError_t sfDevGMX02B::getAlertHysteresis_mV ( float & millivolts)

Get the alert hysteresis as a sensor-output voltage band.

Parameters
millivoltsOutput reference that receives the hysteresis in millivolts.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getAlertLowLimit()

sfTkError_t sfDevGMX02B::getAlertLowLimit ( uint16_t & counts)

Get the alert low limit.

Parameters
countsOutput reference that receives the threshold in raw ADC counts.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getAlertStatus()

sfTkError_t sfDevGMX02B::getAlertStatus ( bool & underRange,
bool & overRange )

Read the raw alert status flags.

Direction-neutral. See getGasAlert() for the part-aware version.

Parameters
underRangeOutput reference set to true if the under-range alert is active.
overRangeOutput reference set to true if the over-range alert is active.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getAlertTriggered()

bool sfDevGMX02B::getAlertTriggered ( void )

Get the ADC alert flag from the most recent readMeasurement().

Bit D15 of the conversion result register. Only reported when the alert flag is enabled with enableAlertFlag(); reflects an alert condition in the Alert Status register.

Returns
true if an alert condition was flagged, false otherwise.

◆ getCleanAirResistance_Ohm()

float sfDevGMX02B::getCleanAirResistance_Ohm ( void )

Get the stored clean-air resistance (R0).

Returns
Clean-air resistance in ohms, or 0 if none has been set.

◆ getConcentration_ppm()

sfTkError_t sfDevGMX02B::getConcentration_ppm ( float & ppm)

Get the estimated target gas concentration.

Only meaningful after setResponseCurve() and a clean-air reference.

Parameters
ppmOutput reference that receives the concentration in ppm.
Returns
::ksfTkErrOk on success, or ::ksfTkErrFail if no curve has been set with setResponseCurve(), or no clean-air reference exists.

◆ getCycleTime()

sfTkError_t sfDevGMX02B::getCycleTime ( sfe_gmx02b_cycle_time_t & cycleTime)

Get the automatic conversion cycle time.

Parameters
cycleTimeOutput reference that receives the current setting.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getDefaultAddress()

uint8_t sfDevGMX02B::getDefaultAddress ( void )

Get the factory-default I2C address for the current sensor variant.

Returns
The 7-bit address.

◆ getGasAlert()

sfTkError_t sfDevGMX02B::getGasAlert ( bool & gasDetected)

Read the hardware alert status as a single "gas detected" flag.

Maps the ADC's under-range / over-range flags through the part's curve direction.

Parameters
gasDetectedOutput reference set true if the gas-side alert is active.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getGasResponse()

sfTkError_t sfDevGMX02B::getGasResponse ( float & response)

Get the direction-normalized gas response from the most recent readMeasurement().

Defined as R0/Rs for falling-Rs parts and Rs/R0 for rising-Rs parts, so the result is approximately 1.0 in clean air and RISES with target gas on every family member. This is also the direction in which the datasheets quote sensitivity, so it compares directly against getRatedSensitivity():

Parameters
responseOutput reference that receives the gas response ratio.
Returns
::ksfTkErrOk on success, or ::ksfTkErrFail if no clean-air resistance has been set or the reading is off scale.

◆ getHighestConversion()

sfTkError_t sfDevGMX02B::getHighestConversion ( uint16_t & counts)

Get the highest conversion result recorded in automatic conversion mode.

Direction-neutral raw register access. Only updated while automatic conversion mode is active.

Parameters
countsOutput reference that receives the highest recorded raw ADC value.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getLoadResistance_Ohm()

float sfDevGMX02B::getLoadResistance_Ohm ( void )

Get the configured load resistance.

Returns
Load resistance in ohms.

◆ getLowestConversion()

sfTkError_t sfDevGMX02B::getLowestConversion ( uint16_t & counts)

Get the lowest conversion result recorded in automatic conversion mode.

Direction-neutral raw register access. Only updated while automatic conversion mode is active.

Parameters
countsOutput reference that receives the lowest recorded raw ADC value.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getPartInfo()

const sfe_gmx02b_part_t * sfDevGMX02B::getPartInfo ( void )

Get the descriptor for the current sensor variant.

Returns
Pointer to the const descriptor. Never null.

◆ getPeakGasCounts()

sfTkError_t sfDevGMX02B::getPeakGasCounts ( uint16_t & counts)

Get the peak GAS conversion recorded in automatic conversion mode.

Reads whichever hardware extremum register corresponds to "most gas" for this part: the highest conversion on falling-Rs parts, the lowest on the GM-102B. Only updated while automatic conversion mode is active.

Parameters
countsOutput reference that receives the raw ADC value.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getPeakGasVoltage_V()

sfTkError_t sfDevGMX02B::getPeakGasVoltage_V ( float & volts)

Get the peak gas conversion as a sensor output voltage.

Same as getPeakGasCounts(), converted with countsToVoltage_V().

Parameters
voltsOutput reference that receives the peak sensor output voltage in volts.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ getRangeMax_ppm()

float sfDevGMX02B::getRangeMax_ppm ( void )

Get the high end of the part's detection range.

Returns
Concentration in ppm.

◆ getRangeMin_ppm()

float sfDevGMX02B::getRangeMin_ppm ( void )

Get the low end of the part's detection range.

Returns
Concentration in ppm.

◆ getRatedConcentration_ppm()

float sfDevGMX02B::getRatedConcentration_ppm ( void )

Get the concentration at which getRatedSensitivity() is specified.

Returns
Concentration in ppm.

◆ getRatedSensitivity()

float sfDevGMX02B::getRatedSensitivity ( void )

Get the datasheet response ratio bound for this part.

Expressed in the same direction as getGasResponse(): the response the part is specified to reach at getRatedConcentration_ppm(). Useful as a sanity check on a calibration, or as a starting point for an alert threshold.

Returns
The rated response ratio (dimensionless).

◆ getRatio()

sfTkError_t sfDevGMX02B::getRatio ( float & ratio)

Get the raw Rs/R0 ratio from the most recent readMeasurement().

The unnormalized physical ratio, as plotted on the datasheet sensitivity curves: approximately 1.0 in clean air, falling with gas on eight parts and rising with gas on the GM-102B. For a direction-independent quantity, use getGasResponse().

Parameters
ratioOutput reference that receives Rs/R0.
Returns
::ksfTkErrOk on success, or ::ksfTkErrFail if no clean-air resistance has been set or the reading is off scale.

◆ getRaw()

uint16_t sfDevGMX02B::getRaw ( void )

Get the raw 10-bit ADC value from the most recent readMeasurement().

Note
Counts rise with gas on eight of the nine parts and FALL with gas on the GM-102B. See rsRisesWithGas().
Returns
Raw ADC counts (0 to 1023).

◆ getSensorName()

const char * sfDevGMX02B::getSensorName ( void )

Get a printable name for the current sensor variant.

Returns
A string such as "GM-602B".

◆ getSensorResistance_Ohm()

sfTkError_t sfDevGMX02B::getSensorResistance_Ohm ( float & ohms)

Get the sensing element resistance (Rs) from the most recent readMeasurement().

Rs is computed from the load resistor divider: Rs = RL x (1024 - counts) / counts. The supply voltage cancels out of this expression, so only the load resistance (see setLoadResistance_Ohm()) affects the result.

Parameters
ohmsOutput reference that receives the sensor resistance in ohms.
Returns
::ksfTkErrOk on success, or ::ksfTkErrFail if the cached reading is zero counts (resistance too high to measure).

◆ getSensorType()

sfe_gmx02b_sensor_t sfDevGMX02B::getSensorType ( void )

Get the declared sensor variant.

Returns
The sensor variant.

◆ getSupplyVoltage_V()

float sfDevGMX02B::getSupplyVoltage_V ( void )

Get the configured sensing circuit supply voltage.

Returns
Supply voltage in volts (default 3.3 V).

◆ getTargetGas()

const char * sfDevGMX02B::getTargetGas ( void )

Get a printable target gas description for the current sensor variant.

Returns
A string such as "H2S".

◆ getVoltage_V()

float sfDevGMX02B::getVoltage_V ( void )

Get the sensor output voltage from the most recent readMeasurement().

The voltage across the board's load resistor, computed as counts / 1024 x supply voltage (see setSupplyVoltage_V()).

Returns
Sensor output voltage in volts.

◆ isConnected()

bool sfDevGMX02B::isConnected ( void )

Check whether the board's ADC is connected and responding.

Verifies that the device at the configured address has the register signature of an ADC101C021 (see probeADC()). begin() calls this, so a successful begin() means the board responded with a valid register signature.

Note
Neither the ADC101C021 nor the Winsen sensing element has an ID register. The register signature confirms the ADC is present, but not which gas sensor is connected to it.
Returns
true if the device responds and its register signature matches.

◆ isInRange()

bool sfDevGMX02B::isInRange ( float ppm)

Check whether a concentration falls inside the part's rated detection range.

Parameters
ppmConcentration to test.
Returns
true if rangeMin <= ppm <= rangeMax.

◆ measureCleanAirResistance()

sfTkError_t sfDevGMX02B::measureCleanAirResistance ( float & r0,
uint8_t samples = kCleanAirSamples,
uint16_t sampleDelayMs = kCleanAirSampleDelayMs )

Measure and store the clean-air sensor resistance (R0).

Averages several ADC readings taken in clean air and stores the resulting sensor resistance as R0, the reference for getRatio() and getGasResponse(). Call this in known-clean air after the sensor has been powered and preheated long enough for its output to stabilize.

Parameters
r0Output reference that receives the measured clean-air resistance in ohms.
samplesNumber of readings to average (default 16; 0 is treated as 1).
sampleDelayMsDelay between readings in milliseconds (default 50).
Returns
::ksfTkErrOk on success, ::ksfTkErrFail if the readings average to zero counts (resistance too high to measure), or an error code on a communication failure.

◆ probeADC()

bool sfDevGMX02B::probeADC ( bool assumeUnconfigured = false)

Check that the responding device looks like an ADC101C021.

The ADC101C021 carries its 10-bit values in bits 11:2 of each 16-bit register, so D1:D0 and D15:D12 read back as zero on every value register, and D1 of the 8-bit configuration register is reserved-zero. That is 31 required-zero bits across six registers.

This check is read-only. Addresses 0x50 to 0x57 are also the classic 24-series EEPROM block (SparkFun's own Qwiic EEPROM defaults to 0x50), and writing a probe pattern to a register that turned out to be an EEPROM word address would corrupt a customer's data.

Note
This confirms the ADC, not the gas sensor. A fully zeroed EEPROM would also pass.
Parameters
assumeUnconfiguredIf true, additionally require the alert limit registers to hold their power-on values (low = 0, high = 1023). This is a stronger check, but only valid before the sketch has configured the alert function.
Returns
true if the device's registers are consistent with an ADC101C021.

◆ readMeasurement()

sfTkError_t sfDevGMX02B::readMeasurement ( void )

Read one conversion from the ADC and cache the result.

Reads the conversion result register and stores the 10-bit value and the alert flag bit. In normal mode (automatic conversion disabled), reading this register is what triggers the next conversion. In automatic conversion mode, this returns the most recent conversion.

Returns
::ksfTkErrOk on success, or an error code on failure.

◆ readRegister16()

sfTkError_t sfDevGMX02B::readRegister16 ( uint8_t reg,
uint16_t & value )
protected

Read a 16-bit register from the ADC (most significant byte first).

Parameters
regThe register pointer value.
valueOutput reference that receives the register contents.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ readRegister8()

sfTkError_t sfDevGMX02B::readRegister8 ( uint8_t reg,
uint8_t & value )
protected

Read an 8-bit register from the ADC.

Parameters
regThe register pointer value.
valueOutput reference that receives the register contents.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ readValueRegister()

sfTkError_t sfDevGMX02B::readValueRegister ( uint8_t reg,
uint16_t & counts )
protected

Read a 10-bit value register (value stored in bits 11:2).

Parameters
regThe register pointer value.
countsOutput reference that receives the 10-bit value.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ resistanceToCounts()

uint16_t sfDevGMX02B::resistanceToCounts ( float ohms)

Convert a sensor resistance into the equivalent 10-bit ADC counts.

The inverse of getSensorResistance_Ohm(): counts = 1024 x RL / (Rs + RL).

Parameters
ohmsSensor resistance in ohms.
Returns
Equivalent ADC counts (0 to 1023).

◆ responseToCounts()

sfTkError_t sfDevGMX02B::responseToCounts ( float response,
uint16_t & counts )

Convert a gas response ratio into the equivalent 10-bit ADC counts.

Applies the part's curve direction and the stored clean-air resistance, then the divider. Requires a clean-air reference.

Parameters
responseGas response ratio, in getGasResponse() units.
countsOutput reference that receives the equivalent raw ADC value.
Returns
::ksfTkErrOk on success, or ::ksfTkErrFail if no clean-air reference is set or response is not positive.

◆ rsRisesWithGas()

bool sfDevGMX02B::rsRisesWithGas ( void )

Report whether Rs rises or falls with target gas concentration.

True only for the GM-102B (NO2, an oxidizing gas). Callers working directly in ADC counts or with the raw alert registers need this to interpret their results; callers using getGasResponse() and friends do not.

Returns
true if sensor resistance increases with gas concentration.

◆ setAlertHighLimit()

sfTkError_t sfDevGMX02B::setAlertHighLimit ( uint16_t counts)

Set the alert high limit (over-range threshold).

Direction-neutral raw register access. If a conversion rises above this value, an over-range alert is generated. The power-on default is 1023 (never triggers). On eight of the nine parts this is the gas-side limit; on the GM-102B it is the clean-air side.

Parameters
countsThreshold in raw ADC counts (0 to 1023). See voltageToCounts().
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ setAlertHysteresis()

sfTkError_t sfDevGMX02B::setAlertHysteresis ( uint16_t counts)

Set the alert hysteresis.

After an alert, the reading must move back inside the violated limit by more than this value before the alert self-clears (unless alert hold is enabled, in which case alerts only clear via clearAlertStatus()).

Parameters
countsHysteresis in raw ADC counts (0 to 1023).
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ setAlertHysteresis_mV()

sfTkError_t sfDevGMX02B::setAlertHysteresis_mV ( float millivolts)

Set the alert hysteresis as a sensor-output voltage band.

Convenience form of setAlertHysteresis(), which takes raw counts. Hysteresis is linear in the sensor's output voltage, so millivolts convert exactly.

Parameters
millivoltsHysteresis in millivolts of sensor output.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ setAlertLowLimit()

sfTkError_t sfDevGMX02B::setAlertLowLimit ( uint16_t counts)

Set the alert low limit (under-range threshold).

Direction-neutral raw register access. If a conversion falls below this value, an under-range alert is generated. The power-on default is 0 (never triggers). On the GM-102B this is the gas-side limit; on every other part it is the clean-air side.

Parameters
countsThreshold in raw ADC counts (0 to 1023). See voltageToCounts().
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ setAlertPinActiveHigh()

sfTkError_t sfDevGMX02B::setAlertPinActiveHigh ( bool activeHigh)

Set the active polarity of the ALERT output pin.

Parameters
activeHightrue for active high, false for active low (default).
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ setCleanAirResistance_Ohm()

void sfDevGMX02B::setCleanAirResistance_Ohm ( float ohms)

Set the clean-air resistance (R0) directly.

Use this to restore a previously measured R0 (for example, one saved to EEPROM) instead of recalibrating with measureCleanAirResistance().

Parameters
ohmsClean-air resistance in ohms.

◆ setCycleTime()

sfTkError_t sfDevGMX02B::setCycleTime ( sfe_gmx02b_cycle_time_t cycleTime)

Set the automatic conversion cycle time (enables / disables automatic mode).

With a non-zero cycle time, the ADC converts continuously on its own: the alert limits are evaluated and the lowest / highest conversion registers are updated after every conversion, with no I2C traffic required. Pass GM_CYCLE_DISABLED to return to normal mode. Slower cycle times use less power; GM_CYCLE_TIME_2048 is sufficient for a slow-responding MOS gas sensor.

Parameters
cycleTimeThe conversion interval (see sfe_gmx02b_cycle_time_t).
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ setGasAlertResponse()

sfTkError_t sfDevGMX02B::setGasAlertResponse ( float response)

Set a hardware gas threshold in gas response units.

Converts response into ADC counts and writes it to whichever limit register corresponds to "more gas" for this part: the high limit on falling-Rs parts, the low limit on the GM-102B. Pair with getGasAlert(), which maps the status flags back the same way.

Note
Writes one limit register and leaves the other alone. If you previously set the other limit by hand, it stays active.
Parameters
responseThreshold in getGasResponse() units (for example 2.0 for "twice the clean-air response").
Returns
::ksfTkErrOk on success, ::ksfTkErrFail if no clean-air reference is set, or an error code on a communication failure.

◆ setLoadResistance_Ohm()

void sfDevGMX02B::setLoadResistance_Ohm ( float ohms)

Override the load resistance (RL) used by getSensorResistance_Ohm().

Defaults to the value in the current part's descriptor, so this is only needed for a hand-modified board. Note that setSensorType() resets it to the descriptor value.

Parameters
ohmsLoad resistance in ohms.

◆ setResponseCurve()

void sfDevGMX02B::setResponseCurve ( float a,
float b )

Set a power-law curve that converts gas response into a concentration.

Defines ppm = a x pow(getGasResponse(), b). No coefficients are shipped with this library, and none should be inferred from the datasheets: Winsen publishes no numeric curve data for any GM-x02B part, and the GM-602B manual describes the sensitivity as "non linear, hysteretic and non-repetitive". Fit a and b yourself against known gas concentrations for your part, in your enclosure, at your operating temperature and humidity.

Parameters
aMultiplier.
bExponent.

◆ setSensorType()

bool sfDevGMX02B::setSensorType ( sfe_gmx02b_sensor_t sensor)

Declare which family member is installed.

Also resets the load resistance to the board default for that variant, discarding any prior setLoadResistance_Ohm() override. Does not touch the stored clean-air resistance, which is no longer valid if the part changed; re-run measureCleanAirResistance().

Parameters
sensorThe sensor variant. GM_UNKNOWN and out-of-range values are rejected.
Returns
true if the variant was accepted.

◆ setSupplyVoltage_V()

void sfDevGMX02B::setSupplyVoltage_V ( float volts)

Set the sensing circuit supply voltage used by getVoltage_V(), voltageToCounts() and countsToVoltage_V().

The ADC101C021 uses its supply as the conversion reference. On the SparkFun boards both the ADC and the sensing loop run from the 3.3 V Qwiic rail (the default).

Parameters
voltsSupply / reference voltage in volts.

◆ updateConfiguration()

sfTkError_t sfDevGMX02B::updateConfiguration ( uint8_t mask,
uint8_t value )
protected

Read-modify-write bits of the 8-bit configuration register.

Parameters
maskThe bits to modify.
valueThe new value of the masked bits (already shifted into position).
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ voltageToCounts()

uint16_t sfDevGMX02B::voltageToCounts ( float volts)

Convert a voltage into the equivalent 10-bit ADC counts.

Useful for expressing alert limits in volts. Uses the configured supply voltage and clamps the result to the valid 0 to 1023 range.

Parameters
voltsVoltage to convert.
Returns
Equivalent ADC counts (0 to 1023).

◆ writeRegister16()

sfTkError_t sfDevGMX02B::writeRegister16 ( uint8_t reg,
uint16_t value )
protected

Write a 16-bit register on the ADC (most significant byte first).

Parameters
regThe register pointer value.
valueThe value to write.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ writeRegister8()

sfTkError_t sfDevGMX02B::writeRegister8 ( uint8_t reg,
uint8_t value )
protected

Write an 8-bit register on the ADC.

Parameters
regThe register pointer value.
valueThe value to write.
Returns
::ksfTkErrOk on success, or an error code on failure.

◆ writeValueRegister()

sfTkError_t sfDevGMX02B::writeValueRegister ( uint8_t reg,
uint16_t counts )
protected

Write a 10-bit value register (value stored in bits 11:2).

Parameters
regThe register pointer value.
countsThe 10-bit value to write (clamped to 1023).
Returns
::ksfTkErrOk on success, or an error code on failure.

Member Data Documentation

◆ _alertFlag

bool sfDevGMX02B::_alertFlag = false
protected

Alert flag (bit D15) from the conversion result.

◆ _cleanAirResistance

float sfDevGMX02B::_cleanAirResistance = 0.0f
protected

Stored clean-air sensor resistance R0 (Ohm); 0 = not set.

◆ _counts

uint16_t sfDevGMX02B::_counts = 0
protected

Raw 10-bit ADC value.

◆ _curveA

float sfDevGMX02B::_curveA = 0.0f
protected

Multiplier; 0 = no curve set.

◆ _curveB

float sfDevGMX02B::_curveB = 0.0f
protected

Exponent.

◆ _loadResistance

float sfDevGMX02B::_loadResistance = 0.0f
protected

Load resistor RL (Ohm). Set from the part descriptor.

◆ _part

const sfe_gmx02b_part_t* sfDevGMX02B::_part = nullptr
protected

Descriptor for _sensorType. Never null after construction.

◆ _sensorType

sfe_gmx02b_sensor_t sfDevGMX02B::_sensorType = GM_602B
protected

Declared sensor variant.

◆ _supplyVoltage

float sfDevGMX02B::_supplyVoltage = kSupplyVoltageDefault
protected

ADC reference / sensing loop supply (V).

◆ _theBus

sfTkIBus* sfDevGMX02B::_theBus
protected

Pointer to the communication bus device.

◆ kAdcFullScale

const uint16_t sfDevGMX02B::kAdcFullScale = 1024
staticprotected

10-bit ADC full-scale count (1 LSB = VA / 1024).

◆ kAdcFullScaleInv

float sfDevGMX02B::kAdcFullScaleInv = 1.0f / 1024.0f
staticconstexprprotected

Precomputed 1 / full scale.

◆ kAdcMaxCounts

const uint16_t sfDevGMX02B::kAdcMaxCounts = 1023
staticprotected

Maximum 10-bit ADC value.

◆ kAlertFlagMask

const uint16_t sfDevGMX02B::kAlertFlagMask = 0x8000
staticprotected

Alert flag (D15) in the conversion result.

◆ kAlertStatusOverRange

const uint8_t sfDevGMX02B::kAlertStatusOverRange = 0x02
staticprotected

Over-range alert flag.

◆ kAlertStatusUnderRange

const uint8_t sfDevGMX02B::kAlertStatusUnderRange = 0x01
staticprotected

Under-range alert flag.

◆ kCleanAirSampleDelayMs

const uint16_t sfDevGMX02B::kCleanAirSampleDelayMs = 50
staticprotected

Default delay between R0 readings (ms).

◆ kCleanAirSamples

const uint8_t sfDevGMX02B::kCleanAirSamples = 16
staticprotected

Default readings averaged for R0.

◆ kConfigAlertFlagEnable

const uint8_t sfDevGMX02B::kConfigAlertFlagEnable = 0x08
staticprotected

Conversion result alert flag enable (D3).

◆ kConfigAlertHold

const uint8_t sfDevGMX02B::kConfigAlertHold = 0x10
staticprotected

Alert hold enable (D4).

◆ kConfigAlertPinEnable

const uint8_t sfDevGMX02B::kConfigAlertPinEnable = 0x04
staticprotected

ALERT pin enable (D2).

◆ kConfigCycleTimeMask

const uint8_t sfDevGMX02B::kConfigCycleTimeMask = 0xE0
staticprotected

Cycle time field (D7:5).

◆ kConfigCycleTimeShift

const uint8_t sfDevGMX02B::kConfigCycleTimeShift = 5
staticprotected

Cycle time field bit position.

◆ kConfigPolarity

const uint8_t sfDevGMX02B::kConfigPolarity = 0x01
staticprotected

ALERT pin polarity: 1 = active high (D0).

◆ kConfigReserved

const uint8_t sfDevGMX02B::kConfigReserved = 0x02
staticprotected

Reserved, reads zero (D1).

◆ kRegAlertStatus

const uint8_t sfDevGMX02B::kRegAlertStatus = 0x01
staticprotected

Alert status flags (8-bit).

◆ kRegConfiguration

const uint8_t sfDevGMX02B::kRegConfiguration = 0x02
staticprotected

Configuration (8-bit).

◆ kRegConversionResult

const uint8_t sfDevGMX02B::kRegConversionResult = 0x00
staticprotected

Conversion result (16-bit, read only).

◆ kRegHighestConversion

const uint8_t sfDevGMX02B::kRegHighestConversion = 0x07
staticprotected

Highest conversion seen (16-bit).

◆ kRegHighLimit

const uint8_t sfDevGMX02B::kRegHighLimit = 0x04
staticprotected

Alert high limit (16-bit).

◆ kRegHysteresis

const uint8_t sfDevGMX02B::kRegHysteresis = 0x05
staticprotected

Alert hysteresis (16-bit).

◆ kRegLowestConversion

const uint8_t sfDevGMX02B::kRegLowestConversion = 0x06
staticprotected

Lowest conversion seen (16-bit).

◆ kRegLowLimit

const uint8_t sfDevGMX02B::kRegLowLimit = 0x03
staticprotected

Alert low limit (16-bit).

◆ kSupplyVoltageDefault

float sfDevGMX02B::kSupplyVoltageDefault = 3.3f
staticconstexprprotected

Qwiic 3.3 V rail powers ADC and sensing loop.

◆ kValueMask

const uint16_t sfDevGMX02B::kValueMask = 0x03FF
staticprotected

Mask for the 10-bit value (after shifting).

◆ kValueReservedMask

const uint16_t sfDevGMX02B::kValueReservedMask = 0xF003
staticprotected

D15:D12 and D1:D0.

◆ kValueShift

const uint8_t sfDevGMX02B::kValueShift = 2
staticprotected

Bit position of the 10-bit value.


The documentation for this class was generated from the following files: