### Enable Serial Debugging in Setup Source: https://github.com/miguel5612/mqsensorslib/blob/master/README.md Call this function in the setup() to enable serial debugging for the sensor. ```arduino MQ2.serialDebug(true); ``` -------------------------------- ### Initialize MQ Sensor in setup() Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Call `init()` in the `setup()` function to configure the analog pin as an input. This method should not be called when using an external ADC. ```cpp #include #define Board "Arduino UNO" #define Pin A0 #define Type "MQ-2" #define VRes 5 #define ADCBit 10 MQUnifiedsensor MQ2(Board, VRes, ADCBit, Pin, Type); void setup() { Serial.begin(9600); MQ2.setRegressionMethod(1); // Exponential: PPM = a * ratio^b MQ2.setA(574.25); MQ2.setB(-2.222); // LPG coefficients from datasheet MQ2.init(); // Sets Pin as INPUT } ``` -------------------------------- ### Run End-to-End Tests Source: https://github.com/miguel5612/mqsensorslib/blob/master/README.md Navigate to the example directory for MQ-3 to run end-to-end tests. This can help re-adjust values and improve features. ```bash Examples/MQ-3 ``` -------------------------------- ### init() Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Configures the analog pin as an input. This method must be called in `setup()` when using the board's built-in ADC. Do not call this method when using an external ADC. ```APIDOC ## `init()` Configures the analog pin as an input. Must be called in `setup()` when using the board's built-in ADC. **Do not call this method when using an external ADC.** ```cpp #include #define Board "Arduino UNO" #define Pin A0 #define Type "MQ-2" #define VRes 5 #define ADCBit 10 MQUnifiedsensor MQ2(Board, VRes, ADCBit, Pin, Type); void setup() { Serial.begin(9600); MQ2.setRegressionMethod(1); // Exponential: PPM = a * ratio^b MQ2.setA(574.25); MQ2.setB(-2.222); // LPG coefficients from datasheet MQ2.init(); // Sets Pin as INPUT } ``` ``` -------------------------------- ### Clone MQSensorsLib Repository Source: https://github.com/miguel5612/mqsensorslib/blob/master/README.md Use this command to clone the MQSensorsLib repository to your local machine. Ensure you have Git installed. ```bash git clone https://github.com/miguel5612/MQSensorsLib ``` -------------------------------- ### Run Coding Style Tests Source: https://github.com/miguel5612/mqsensorslib/blob/master/README.md Use this command to run coding style tests and generate statistics validation. This example is for MQ-board.ino. ```bash Examples/MQ-board.ino ``` -------------------------------- ### Print Diagnostic Information via Serial Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Prints diagnostic information to the Serial port. Call with `true` in `setup()` for a one-time configuration summary, or without arguments in `loop()` for a running tabular display of sensor values. ```cpp void setup() { Serial.begin(9600); // ... sensor init and calibration ... MQ4.serialDebug(true); // Output: // ************************************************************ // MQ sensor reading library for arduino // Sensor: MQ-4 | ADC voltage: 5 VDC | VCC: 5 VDC // ADC Resolution: 10 Bits | R0: 3.86 KΩ | RL: 10 KΩ // Model: Exponential | MQ-4 -> a: 1012.7 | b: -2.786 } void loop() { MQ4.update(); MQ4.readSensor(); MQ4.serialDebug(); // Output row: |ADC | V_eq | Voltage | RS_eq | RS | Ratio_eq | Ratio | PPM_eq | PPM | delay(500); } ``` -------------------------------- ### serialDebug Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Prints diagnostic information to the Serial port. Can be called in setup() for a one-time configuration summary or in loop() for a running display of sensor values. ```APIDOC ## `serialDebug(bool onSetup = false)` Prints diagnostic information to the Serial port. Call with `true` in `setup()` for a one-time configuration summary; call with no argument (or `false`) in `loop()` for a running tabular display of ADC, voltage, RS, ratio, and PPM values. ```cpp void setup() { Serial.begin(9600); // ... sensor init and calibration ... MQ4.serialDebug(true); // Output: // ************************************************************ // MQ sensor reading library for arduino // Sensor: MQ-4 | ADC voltage: 5 VDC | VCC: 5 VDC // ADC Resolution: 10 Bits | R0: 3.86 KΩ | RL: 10 KΩ // Model: Exponential | MQ-4 -> a: 1012.7 | b: -2.786 } void loop() { MQ4.update(); MQ4.readSensor(); MQ4.serialDebug(); // Output row: |ADC | V_eq | Voltage | RS_eq | RS | Ratio_eq | Ratio | PPM_eq | PPM | delay(500); } ``` ``` -------------------------------- ### Set and Get Baseline Resistance R0 Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Manually set the baseline sensor resistance R0 (in kΩ) established during clean air calibration using `setR0()`. Retrieve the stored value with `getR0()`. ```cpp // Load a previously measured R0 from EEPROM instead of re-calibrating #include float storedR0; EEPROM.get(0, storedR0); MQ4.setR0(storedR0); // Verify Serial.print("Loaded R0: "); Serial.println(MQ4.getR0()); // e.g. 3.86018 KΩ ``` -------------------------------- ### Set and Get Load Resistance RL Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Set the load resistance RL on the sensor module using `setRL()`. The default is 10 kΩ and must match the actual resistor value on the breakout board. Retrieve the value with `getRL()`. ```cpp MQ7.setRL(10); // 10 KΩ (default) Serial.println(MQ7.getRL()); // 10.00 ``` -------------------------------- ### Update Sensor Readings Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Reads the analog pin, averaging two samples with a 20 ms interval. This function must be called at the start of every loop iteration when using the built-in ADC. ```cpp void loop() { MQ4.update(); // Reads analogRead(pin), averages samples float ppm = MQ4.readSensor(); Serial.println(ppm); delay(500); } ``` -------------------------------- ### Get Sensor Data Accessors Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Accessors to retrieve the last calculated sensor resistance (RS), configured coefficients (A, B), current voltage, and regression model name. Ensure `update()` and `readSensor()` are called before accessing these values. ```cpp MQ2.update(); MQ2.readSensor(); Serial.print("RS: "); Serial.println(MQ2.getRS()); // e.g. 9.52 KΩ Serial.print("R0: "); Serial.println(MQ2.getR0()); // e.g. 9.83 KΩ Serial.print("a: "); Serial.println(MQ2.getA()); // 574.25 Serial.print("b: "); Serial.println(MQ2.getB()); // -2.222 Serial.print("Vres: "); Serial.println(MQ2.getVoltResolution()); // 5.00 Serial.print("VCC: "); Serial.println(MQ2.getVCC()); // 5.00 Serial.print("Model: ");Serial.println(MQ2.getRegressionMethod()); // "Exponential" ``` -------------------------------- ### Initialize and Read MQ-4 Sensor on Arduino Source: https://github.com/miguel5612/mqsensorslib/blob/master/README.md This snippet demonstrates how to include the library, define hardware and software parameters, initialize the MQ-4 sensor, and read its PPM value. Ensure correct pin and type definitions for your board and sensor. ```cpp #include /************************Hardware Related Macros************************************/ #define Board ("Arduino UNO") #define Pin (A4) //Analog input 4 of your arduino /***********************Software Related Macros************************************/ #define Type ("MQ-4") //MQ4 #define Voltage_Resolution (5) #define ADC_Bit_Resolution (10) // For arduino UNO/MEGA/NANO #define RatioMQ4CleanAir (4.4) //RS / R0 = 60 ppm /*****************************Globals***********************************************/ //Declare Sensor MQUnifiedsensor MQ4(Board, Voltage_Resolution, ADC_Bit_Resolution, Pin, Type); // Setup MQ4.setRegressionMethod("Exponential"); //_PPM = a*ratio^b MQ4.setA(1012.7); MQ4.setB(-2.786); // Configure the equation to to calculate CH4 concentration MQ4.setR0(3.86018237); // Value getted on calibration // Loop MQ4.init(); MQ4.update(); float ppmCH4 = MQ4.readSensor(); ``` -------------------------------- ### Instantiate MQUnifiedsensor Object Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Use the constructor to bind the sensor object to a specific board, ADC configuration, analog pin, and sensor type. Minimal constructors are available for external ADC use. ```cpp // Full constructor: board name, ADC reference voltage, ADC bit resolution, analog pin, sensor type MQUnifiedsensor MQ4("Arduino UNO", 5, 10, A4, "MQ-4"); // Minimal constructor for external ADC use (no built-in analogRead) MQUnifiedsensor MQ135("Arduino UNO", "MQ-135"); // ESP8266 – 3.3 V ADC reference MQUnifiedsensor MQ3("ESP8266", 3.3, 10, A0, "MQ-3"); ``` -------------------------------- ### Constructor Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Instantiates an MQUnifiedsensor object, binding it to a specific board, ADC configuration, analog pin, and sensor type. Multiple constructors are available for different use cases. ```APIDOC ## Constructor Instantiates an `MQUnifiedsensor` object, binding it to a specific board, ADC configuration, analog pin, and sensor type. ```cpp // Full constructor: board name, ADC reference voltage, ADC bit resolution, analog pin, sensor type MQUnifiedsensor MQ4("Arduino UNO", 5, 10, A4, "MQ-4"); // Minimal constructor for external ADC use (no built-in analogRead) MQUnifiedsensor MQ135("Arduino UNO", "MQ-135"); // ESP8266 – 3.3 V ADC reference MQUnifiedsensor MQ3("ESP8266", 3.3, 10, A0, "MQ-3"); ``` ``` -------------------------------- ### setRL(float RL) / getRL() Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Sets the load resistance RL on the sensor module (default 10 kΩ). Must match the actual resistor value on the breakout board. ```APIDOC ## `setRL(float RL)` / `getRL()` Sets the load resistance RL on the sensor module (default 10 kΩ). Must match the actual resistor value on the breakout board. ```cpp MQ7.setRL(10); // 10 KΩ (default) Serial.println(MQ7.getRL()); // 10.00 ``` ``` -------------------------------- ### setRegressionMethod(int method) Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Selects the mathematical regression model used to compute PPM from the RS/R0 ratio. Pass `1` for exponential (`PPM = a * ratio^b`) or `0` for linear (`PPM = pow(10, (log10(ratio) - b) / a)`). ```APIDOC ## `setRegressionMethod(int method)` Selects the mathematical regression model used to compute PPM from the RS/R0 ratio. Pass `1` for exponential (`PPM = a * ratio^b`) or `0` for linear (`PPM = pow(10, (log10(ratio) - b) / a)`). ```cpp MQ4.setRegressionMethod(1); // Exponential (most sensors) MQ4.setA(1012.7); MQ4.setB(-2.786); // CH4 on MQ-4 // Linear model example (MQ-4 alternative curve) MQ4.setRegressionMethod(0); MQ4.setA(-0.318); MQ4.setB(1.133); ``` ``` -------------------------------- ### Set Regression Method for PPM Calculation Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Select the mathematical model for PPM calculation. Use `1` for exponential (`PPM = a * ratio^b`) or `0` for linear (`PPM = pow(10, (log10(ratio) - b) / a)`). Configure `a` and `b` coefficients accordingly. ```cpp MQ4.setRegressionMethod(1); // Exponential (most sensors) MQ4.setA(1012.7); MQ4.setB(-2.786); // CH4 on MQ-4 // Linear model example (MQ-4 alternative curve) MQ4.setRegressionMethod(0); MQ4.setA(-0.318); MQ4.setB(1.133); ``` -------------------------------- ### setA(float a) / setB(float b) Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Set the regression coefficients `a` and `b` for the target gas equation. Values are validated and clamped to safe ranges (`|a| ≤ 1e30`, `|b| ≤ 100`). Change these at runtime to measure multiple gases from a single sensor within one loop iteration. ```APIDOC ## `setA(float a)` / `setB(float b)` Set the regression coefficients `a` and `b` for the target gas equation. Values are validated and clamped to safe ranges (`|a| ≤ 1e30`, `|b| ≤ 100`). Change these at runtime to measure multiple gases from a single sensor within one loop iteration. ```cpp // MQ-135 coefficients for multiple gases (exponential model) // GAS | a | b // CO | 605.18 | -3.937 // Alcohol | 77.255 | -3.18 // CO2 | 110.47 | -2.862 // Toluen | 44.947 | -3.445 // NH4 | 102.2 | -2.473 // Aceton | 34.668 | -3.369 MQUnifiedsensor MQ135("Arduino UNO", 5, 10, A0, "MQ-135"); void loop() { MQ135.update(); MQ135.setA(605.18); MQ135.setB(-3.937); float CO = MQ135.readSensor(); MQ135.setA(77.255); MQ135.setB(-3.18); float Alcohol = MQ135.readSensor(); MQ135.setA(110.47); MQ135.setB(-2.862); float CO2 = MQ135.readSensor() + 400; // +400 ppm atmospheric offset MQ135.setA(44.947); MQ135.setB(-3.445); float Toluen = MQ135.readSensor(); MQ135.setA(102.2); MQ135.setB(-2.473); float NH4 = MQ135.readSensor(); MQ135.setA(34.668); MQ135.setB(-3.369); float Aceton = MQ135.readSensor(); Serial.print("CO: "); Serial.print(CO); Serial.print(" | CO2: "); Serial.print(CO2); Serial.print(" | NH4: "); Serial.println(NH4); delay(500); } ``` ``` -------------------------------- ### setR0(float R0) / getR0() Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Manually assigns the baseline sensor resistance R0 (in kΩ) established during calibration in clean air. Retrieve the stored value with `getR0()`. ```APIDOC ## `setR0(float R0)` / `getR0()` Manually assigns the baseline sensor resistance R0 (in kΩ) established during calibration in clean air. Retrieve the stored value with `getR0()`. ```cpp // Load a previously measured R0 from EEPROM instead of re-calibrating #include float storedR0; EEPROM.get(0, storedR0); MQ4.setR0(storedR0); // Verify Serial.print("Loaded R0: "); Serial.println(MQ4.getR0()); // e.g. 3.86018 KΩ ``` ``` -------------------------------- ### Accessors (getRS, getA, getB, getVoltage, getRegressionMethod) Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Provides accessors to retrieve the last calculated sensor resistance (RS), configured coefficients (A and B), current voltage, and the regression model name. ```APIDOC ## `getRS()` / `getA()` / `getB()` / `getVoltage()` / `getRegressionMethod()` Accessors that return the last-calculated sensor resistance RS, the configured coefficients, current voltage, and the regression model name string. ```cpp MQ2.update(); MQ2.readSensor(); Serial.print("RS: "); Serial.println(MQ2.getRS()); // e.g. 9.52 KΩ Serial.print("R0: "); Serial.println(MQ2.getR0()); // e.g. 9.83 KΩ Serial.print("a: "); Serial.println(MQ2.getA()); // 574.25 Serial.print("b: "); Serial.println(MQ2.getB()); // -2.222 Serial.print("Vres: "); Serial.println(MQ2.getVoltResolution()); // 5.00 Serial.print("VCC: "); Serial.println(MQ2.getVCC()); // 5.00 Serial.print("Model: ");Serial.println(MQ2.getRegressionMethod()); // "Exponential" ``` ``` -------------------------------- ### Set Sensor Supply Voltage and ADC Reference Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Configure the sensor's heater supply voltage and the ADC reference voltage. Typically 3.3V for ESP32. ```cpp MQUnifiedsensor MQ135("ESP32", 3.3, 12, 34, "MQ-135"); MQ135.setVCC(3.3); // Heater supply MQ135.setVoltResolution(3.3); // ADC reference ``` -------------------------------- ### Enable Serial Debugging in Loop Source: https://github.com/miguel5612/mqsensorslib/blob/master/README.md Call this function in the loop() to display serial debug information for the sensor. ```arduino MQ2.serialDebug(); ``` -------------------------------- ### Set Regression Coefficients a and b Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Set the `a` and `b` coefficients for the gas concentration equation. These can be changed at runtime to measure multiple gases from a single sensor. ```cpp // MQ-135 coefficients for multiple gases (exponential model) // GAS | a | b // CO | 605.18 | -3.937 // Alcohol | 77.255 | -3.18 // CO2 | 110.47 | -2.862 // Toluen | 44.947 | -3.445 // NH4 | 102.2 | -2.473 // Aceton | 34.668 | -3.369 MQUnifiedsensor MQ135("Arduino UNO", 5, 10, A0, "MQ-135"); void loop() { MQ135.update(); MQ135.setA(605.18); MQ135.setB(-3.937); float CO = MQ135.readSensor(); MQ135.setA(77.255); MQ135.setB(-3.18); float Alcohol = MQ135.readSensor(); MQ135.setA(110.47); MQ135.setB(-2.862); float CO2 = MQ135.readSensor() + 400; // +400 ppm atmospheric offset MQ135.setA(44.947); MQ135.setB(-3.445); float Toluen = MQ135.readSensor(); MQ135.setA(102.2); MQ135.setB(-2.473); float NH4 = MQ135.readSensor(); MQ135.setA(34.668); MQ135.setB(-3.369); float Aceton = MQ135.readSensor(); Serial.print("CO: "); Serial.print(CO); Serial.print(" | CO2: "); Serial.print(CO2); Serial.print(" | NH4: "); Serial.println(NH4); delay(500); } ``` -------------------------------- ### calibrate Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Calculates the R0 value (sensor resistance in clean air) based on the current sensor voltage reading and the provided ratio in clean air. It's recommended to call this method repeatedly and average the results for better accuracy. ```APIDOC ## `calibrate(float ratioInCleanAir, float correctionFactor = 0.0)` Calculates R0 from the current sensor voltage reading, given the RS/R0 ratio in clean air as listed in the datasheet. Call repeatedly and average the results for accuracy. Returns the computed R0 value. ```cpp #define RatioMQ2CleanAir 9.83 // From MQ-2 datasheet MQUnifiedsensor MQ2("Arduino UNO", 5, 10, A2, "MQ-2"); void setup() { Serial.begin(115200); MQ2.setRegressionMethod(1); MQ2.setA(574.25); MQ2.setB(-2.222); MQ2.init(); Serial.print("Calibrating"); float calcR0 = 0; for (int i = 1; i <= 10; i++) { MQ2.update(); calcR0 += MQ2.calibrate(RatioMQ2CleanAir); Serial.print("."); } MQ2.setR0(calcR0 / 10); Serial.println(" done!"); // Wiring error detection if (isinf(calcR0)) { Serial.println("ERROR: R0 is infinite – check wiring (open circuit)"); while (1); } if (calcR0 == 0) { Serial.println("ERROR: R0 is zero – analog pin shorted to GND"); while (1); } Serial.println("R0 = "); Serial.println(MQ2.getR0()); // Expected output: R0 = 9.xxxx } ``` ``` -------------------------------- ### Calibrate MQ Sensor and Detect Wiring Errors Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Calibrates the sensor by calculating R0 from readings in clean air. It's recommended to call this repeatedly and average the results. Includes checks for wiring errors like open circuits or shorts to GND. ```cpp #define RatioMQ2CleanAir 9.83 // From MQ-2 datasheet MQUnifiedsensor MQ2("Arduino UNO", 5, 10, A2, "MQ-2"); void setup() { Serial.begin(115200); MQ2.setRegressionMethod(1); MQ2.setA(574.25); MQ2.setB(-2.222); MQ2.init(); Serial.print("Calibrating"); float calcR0 = 0; for (int i = 1; i <= 10; i++) { MQ2.update(); calcR0 += MQ2.calibrate(RatioMQ2CleanAir); Serial.print("."); } MQ2.setR0(calcR0 / 10); Serial.println(" done!"); // Wiring error detection if (isinf(calcR0)) { Serial.println("ERROR: R0 is infinite – check wiring (open circuit)"); while (1); } if (calcR0 == 0) { Serial.println("ERROR: R0 is zero – analog pin shorted to GND"); while (1); } Serial.print("R0 = "); Serial.println(MQ2.getR0()); // Expected output: R0 = 9.xxxx } ``` -------------------------------- ### Read Gas Concentration Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Computes and returns the gas concentration in PPM. This core function uses the stored sensor voltage, RS/R0 ratio, regression model, and coefficients. It can optionally apply a correction factor for temperature and humidity. ```cpp // Standard usage void loop() { MQ4.update(); float ppmCH4 = MQ4.readSensor(); // Uses stored a, b, R0, RL Serial.print("CH4 (ppm): "); Serial.println(ppmCH4); delay(500); } ``` ```cpp // With temperature/humidity correction (MQ-135 + DHT22) float getCorrectionFactor(float t, float h) { return 0.00035*t*t - 0.02718*t + 1.39538 - (h - 33.0)*0.0018; } void loop() { float t = 25.0, h = 60.0; // from DHT sensor float cFactor = getCorrectionFactor(t, h); MQ135.update(); float ppm = MQ135.readSensor(false, cFactor); Serial.print("NH4 corrected (ppm): "); Serial.println(ppm); delay(500); } ``` ```cpp // MQ303A (special voltage offset applied internally) MQ303A.update(); float ppm303A = MQ303A.readSensor(true); // isMQ303A=true applies 0.45V offset ``` -------------------------------- ### Validate Sensor Equation with Given Ratio Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Directly evaluates the configured PPM equation for a given RS/R0 ratio without reading the sensor. Useful for unit testing regression coefficients against known datasheet values. ```cpp MQUnifiedsensor mySensor("Arduino UNO", 5, 10, A0, "MQ-7"); mySensor.setRegressionMethod(1); mySensor.setA(99.042); mySensor.setB(-1.518); // CO on MQ-7 // Validate against datasheet: ratio=1.0 should yield ~100 ppm CO float ppm = mySensor.validateEcuation(1.0); Serial.print("Calculated: "); Serial.print(ppm); // ~100 ppm Serial.println(" | Expected: 100"); // Batch test double ratios[] = {1.8, 1.0, 0.4, 0.25}; double expected[] = {50, 100, 400, 1000}; for (int i = 0; i < 4; i++) { float calc = mySensor.validateEcuation(ratios[i]); float err = abs(calc - expected[i]) / expected[i] * 100.0; Serial.print("Ratio "); Serial.print(ratios[i]); Serial.print(" -> "); Serial.print(calc); Serial.print(" ppm | error: "); Serial.print(err); Serial.println("%"); } ``` -------------------------------- ### setADC Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Injects a raw integer ADC count, typically from an external ADC, into the library. The library then converts this count to voltage using the configured `VRes` and bit resolution. This is an alternative to `externalADCUpdate` when your external ADC provides raw counts. ```APIDOC ## `setADC(int value)` Injects a raw integer ADC count (e.g., 0–1023 for 10-bit) as if it were read from the analog pin. An alternative to `externalADCUpdate` when the external ADC provides counts rather than volts. ```cpp // Simulated 10-bit external ADC value int rawADC = 512; // from your I2C/SPI ADC MQ3.setADC(rawADC); // Library converts: volt = rawADC * VRes / (2^bits - 1) float ppm = MQ3.readSensor(); ``` ``` -------------------------------- ### update Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Reads the analog pin, averages two samples taken with a 20 ms interval, and stores the resulting voltage internally. This method must be called at the beginning of each loop iteration when using the built-in ADC. ```APIDOC ## `update()` Reads the analog pin (averages 2 samples with a 20 ms interval) and stores the resulting voltage internally. Must be called at the start of every loop iteration when using the built-in ADC. ```cpp void loop() { MQ4.update(); // Reads analogRead(pin), averages samples float ppm = MQ4.readSensor(); Serial.println(ppm); delay(500); } ``` ``` -------------------------------- ### Inject Raw ADC Count Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Injects a raw integer ADC count from an external ADC, useful when the ADC provides counts instead of volts. The library handles the conversion using the configured voltage resolution and bit depth. ```cpp // Simulated 10-bit external ADC value int rawADC = 512; // from your I2C/SPI ADC MQ3.setADC(rawADC); // Library converts: volt = rawADC * VRes / (2^bits - 1) float ppm = MQ3.readSensor(); ``` -------------------------------- ### Read Sensor with Inverted Ratio (R0/RS) Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Use this variant for sensors like MQ-131 (ozone) where the sensitivity curve is plotted in the inverted direction. It requires setting specific coefficients for the sensor. ```cpp MQUnifiedsensor MQ131("Arduino UNO", 5, 10, A0, "MQ-131"); void setup() { MQ131.setRegressionMethod(1); MQ131.setA(23.943); MQ131.setB(-1.11); // O3 coefficients MQ131.init(); // ... calibration ... } void loop() { MQ131.update(); float ppmO3 = MQ131.readSensorR0Rs(); // Uses R0/RS ratio Serial.print("O3 (ppm): "); Serial.println(ppmO3); delay(500); } ``` -------------------------------- ### setVCC and setVoltResolution Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Configures the sensor's heater supply voltage (VCC) and the ADC reference voltage (VoltResolution). These are crucial for accurate resistance (RS) calculations and voltage conversions. ```APIDOC ## `setVCC(float vcc)` / `setVoltResolution(float vRes)` `setVCC` sets the sensor heater supply voltage (used in RS calculation). `setVoltResolution` sets the ADC reference voltage used to convert raw ADC counts to volts. On ESP8266/ESP32 both are typically 3.3 V. ```cpp // ESP32 at 3.3 V supply and 3.3 V ADC reference MQUnifiedsensor MQ135("ESP32", 3.3, 12, 34, "MQ-135"); MQ135.setVCC(3.3); // Heater supply MQ135.setVoltResolution(3.3); // ADC reference ``` ``` -------------------------------- ### validateEcuation Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Directly evaluates the configured PPM equation for a given RS/R0 ratio value without reading the sensor hardware. Useful for unit testing regression coefficients. ```APIDOC ## `validateEcuation(float ratioInput)` Directly evaluates the configured PPM equation for a given RS/R0 ratio value, without reading the sensor hardware. Useful for unit testing regression coefficients against known datasheet values. ```cpp MQUnifiedsensor mySensor("Arduino UNO", 5, 10, A0, "MQ-7"); mySensor.setRegressionMethod(1); mySensor.setA(99.042); mySensor.setB(-1.518); // CO on MQ-7 // Validate against datasheet: ratio=1.0 should yield ~100 ppm CO float ppm = mySensor.validateEcuation(1.0); Serial.print("Calculated: "); Serial.print(ppm); // ~100 ppm Serial.println(" | Expected: 100"); // Batch test double ratios[] = {1.8, 1.0, 0.4, 0.25}; double expected[] = {50, 100, 400, 1000}; for (int i = 0; i < 4; i++) { float calc = mySensor.validateEcuation(ratios[i]); float err = abs(calc - expected[i]) / expected[i] * 100.0; Serial.print("Ratio "); Serial.print(ratios[i]); Serial.print(" -> "); Serial.print(calc); Serial.print(" ppm | error: "); Serial.print(err); Serial.println("%"); } ``` ``` -------------------------------- ### externalADCUpdate Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Injects a pre-converted voltage value (in volts) obtained from an external ADC, bypassing the library's built-in `analogRead` function. This is useful when using external ADC chips like the ADS1115. ```APIDOC ## `externalADCUpdate(float volt)` Injects a pre-converted voltage (in volts) from an external ADC, bypassing the built-in `analogRead`. Use this with chips like the ADS1115. ```cpp #include #include #include Adafruit_ADS1115 ads; MQUnifiedsensor MQ135("Arduino UNO", "MQ-135"); // Minimal constructor float scaleFactor = 0.1875F; // ADS1115 default gain (mV/count) void setup() { Serial.begin(9600); ads.begin(); MQ135.setRegressionMethod(1); MQ135.setA(605.18); MQ135.setB(-3.937); MQ135.init(); float calcR0 = 0; for (int i = 0; i < 10; i++) { float volts = (ads.readADC_SingleEnded(0) * scaleFactor) / 1000.0; MQ135.externalADCUpdate(volts); calcR0 += MQ135.calibrate(3.6); } MQ135.setR0(calcR0 / 10); } void loop() { float volts = (ads.readADC_SingleEnded(0) * scaleFactor) / 1000.0; MQ135.externalADCUpdate(volts); float CO = MQ135.readSensor(); Serial.print("CO (ppm): "); Serial.println(CO); delay(500); } ``` ``` -------------------------------- ### Inject External ADC Voltage Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Bypasses the built-in analogRead by injecting a pre-converted voltage from an external ADC, such as the ADS1115. Requires including Wire and Adafruit_ADS1X15 libraries. ```cpp #include #include #include Adafruit_ADS1115 ads; MQUnifiedsensor MQ135("Arduino UNO", "MQ-135"); // Minimal constructor float scaleFactor = 0.1875F; // ADS1115 default gain (mV/count) void setup() { Serial.begin(9600); ads.begin(); MQ135.setRegressionMethod(1); MQ135.setA(605.18); MQ135.setB(-3.937); MQ135.init(); float calcR0 = 0; for (int i = 0; i < 10; i++) { float volts = (ads.readADC_SingleEnded(0) * scaleFactor) / 1000.0; MQ135.externalADCUpdate(volts); calcR0 += MQ135.calibrate(3.6); } MQ135.setR0(calcR0 / 10); } void loop() { float volts = (ads.readADC_SingleEnded(0) * scaleFactor) / 1000.0; MQ135.externalADCUpdate(volts); float CO = MQ135.readSensor(); Serial.print("CO (ppm): "); Serial.println(CO); delay(500); } ``` -------------------------------- ### MQ-7/MQ-309A Two-Voltage Heater Cycle Control Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Manages the alternating heater voltages required for MQ-7 and MQ-309A sensors. Uses PWM via a MOSFET to control the heater voltage between 5V and 1.4V for specific durations. ```cpp #include #define PWMPin 5 MQUnifiedsensor MQ7("Arduino UNO", 5, 10, A0, "MQ-7"); unsigned long oldTime = 0; void setup() { Serial.begin(9600); pinMode(PWMPin, OUTPUT); MQ7.setRegressionMethod(1); MQ7.setA(99.042); MQ7.setB(-1.518); // CO MQ7.init(); float calcR0 = 0; for (int i = 1; i <= 10; i++) { MQ7.update(); calcR0 += MQ7.calibrate(27.5); // RatioMQ7CleanAir } MQ7.setR0(calcR0 / 10); if (isinf(calcR0) || calcR0 == 0) { while(1); } } void loop() { // Phase 1: 5 V heater for 60 s oldTime = millis(); while (millis() - oldTime <= 60000) { analogWrite(PWMPin, 255); // 100% duty = 5 V MQ7.update(); float ppm = MQ7.readSensor(); Serial.print("CO (ppm): "); Serial.println(ppm); delay(500); } // Phase 2: 1.4 V heater for 90 s oldTime = millis(); while (millis() - oldTime <= 90000) { analogWrite(PWMPin, 20); // ~8% duty ≈ 1.4 V MQ7.update(); float ppm = MQ7.readSensor(); Serial.print("CO (ppm): "); Serial.println(ppm); delay(500); } // Total cycle: 2.5 minutes } ``` -------------------------------- ### readSensor Source: https://context7.com/miguel5612/mqsensorslib/llms.txt The primary function for computing and returning the gas concentration in parts per million (PPM). It uses the internally stored sensor voltage, R0 value, and configured regression coefficients. It can optionally apply a correction factor for temperature and humidity compensation, or handle special sensor types like the MQ303A. ```APIDOC ## `readSensor(bool isMQ303A = false, float correctionFactor = 0.0, bool injected = false)` Core function: computes RS from the stored sensor voltage, calculates the RS/R0 ratio, and returns the gas concentration in PPM using the configured regression model and coefficients. An optional `correctionFactor` adjusts the ratio for temperature/humidity compensation. ```cpp // Standard usage void loop() { MQ4.update(); float ppmCH4 = MQ4.readSensor(); // Uses stored a, b, R0, RL Serial.print("CH4 (ppm): "); Serial.println(ppmCH4); delay(500); } // With temperature/humidity correction (MQ-135 + DHT22) float getCorrectionFactor(float t, float h) { return 0.00035*t*t - 0.02718*t + 1.39538 - (h - 33.0)*0.0018; } void loop() { float t = 25.0, h = 60.0; // from DHT sensor float cFactor = getCorrectionFactor(t, h); MQ135.update(); float ppm = MQ135.readSensor(false, cFactor); Serial.print("NH4 corrected (ppm): "); Serial.println(ppm); delay(500); } // MQ303A (special voltage offset applied internally) MQ303A.update(); float ppm303A = MQ303A.readSensor(true); // isMQ303A=true applies 0.45V offset ``` ``` -------------------------------- ### readSensorR0Rs Source: https://context7.com/miguel5612/mqsensorslib/llms.txt Reads the sensor value using the inverted R0/RS ratio. This is useful for sensors like MQ-131 where the sensitivity curve is plotted in the inverted direction. ```APIDOC ## `readSensorR0Rs(float correctionFactor = 0.0)` Variant of `readSensor` that uses the inverted ratio **R0/RS** instead of RS/R0. Required for certain sensors like MQ-131 (ozone) where the sensitivity curve is plotted in the inverted direction. ```cpp // MQ-131 Ozone reading MQUnifiedsensor MQ131("Arduino UNO", 5, 10, A0, "MQ-131"); void setup() { MQ131.setRegressionMethod(1); MQ131.setA(23.943); MQ131.setB(-1.11); // O3 coefficients MQ131.init(); // ... calibration ... } void loop() { MQ131.update(); float ppmO3 = MQ131.readSensorR0Rs(); // Uses R0/RS ratio Serial.print("O3 (ppm): "); Serial.println(ppmO3); delay(500); } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.