MQSensorsLib C++ Library

repository·master·Indexed 42 days ago

https://github.com/miguel5612/mqsensorslib

A unified C++ library for reading signals from MQ-series gas sensors using Arduino, Genuino, ESP8266, and ESP32 boards. It provides the MQUnifiedsensor class to handle calibration, regression methods (Exponential and Linear), and environmental correction factors for calculating gas concentrations in PPM. Features include support for external ADCs, serial debugging, and specific configurations for sensors like MQ-4, MQ-7, and MQ-135.

Tokens
2.5K
Snippets
6
Records
12
Agent score
53%

What's inside MQSensorsLib

  1. Quickstart: Using MQSensorsLib with an MQ-4 sensor

    master

    To use the library, include MQUnifiedsensor.h and define your hardware and software parameters. You must specify the board type, the analog pin, the sensor type, the voltage resolution, and the ADC bit resolution. After declaring the sensor object, configure the regression method (e.g., "Exponential"), set the coefficients (A and B) for the gas concentration equation, and provide the $R_0$ value obtained from calibration. Finally, call .init() in setup and .update() in the loop to read the sensor values.

    //Include the library
    #include <MQUnifiedsensor.h>
    /************************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();
  2. Wiring MQ Sensors to Arduino and ESP boards

    master

    Sensor Connections

    • VCC: Connect to 5V power supply (+).
    • GND: Connect to GND ground (-).
    • AO: Connect to the Analog Output of the sensor.

    Note: If the sensor uses a different supply voltage than the ADC reference, use yourSensor.setVCC(<voltage>);.

    Board Specifics

    • Arduino: Standard analog connection. Note that MQ-7 and MQ-309A require two different voltages for the heater; these can be supplied via PWM or separate DC signals.
    • ESP8266 / ESP32: Connect via analog pins as per board diagrams.
    • ESP32 WROOM 32D: Does not require an external power supply. Connect A0 to PIN36, Vcc to 3v3, and GND to any GND port. (Note: If using WiFi, refer to the ESP2/ESP32_WROOM_32 folder for fixes).
  3. Enable Serial Debugging for troubleshooting

    master

    You can enable detailed serial output to troubleshoot calculations and hardware/software characteristics. This is useful for seeing the library's internal steps and results.

    1. In setup(), call MQx.serialDebug(true); (replace MQx with your sensor object).
    2. In loop(), call MQx.serialDebug();.

    Debug Output Colors:

    • Yellow: Calibration status.
    • Green: Hardware and software characteristics.
    • Red: Library calculation headers.
    // In setup
    MQ2.serialDebug(true); 
    
    // In loop
    MQ2.serialDebug(); 
  4. Adjust readings for temperature and humidity dependence

    master

    To account for environmental factors like temperature and humidity, the library allows for an optional "correction factor".

    When the sensor datasheet provides coefficients for environmental compensation, you can pass this factor to the following functions:

    • calibrate(float correctionFactor)
    • readSensorR0Rs(float correctionFactor)

    This allows you to adjust the sensor's sensitivity and baseline based on the current environmental conditions.

  5. Avoid 'ovf' (overflow) errors when reading CH4 with MQ-3 sensors

    master

    When using an MQ-3 sensor to read CH4, very high values passed to setA and setB can cause overflow errors (ovf).

    To prevent this:

    1. Use correct exponential notation: In C++, 2*10^31 is not the same as 2e31. Use 2e31 or pow(10, 31) for large coefficients.
    2. Check float ranges: Ensure parameters do not exceed the maximum range of a float.
    3. Library updates: If using version 3.0.0 or later, the library includes input validation, overflow prediction via logarithms, and double-precision calculations to mitigate this issue.
  6. Troubleshoot calibration 'Connection issue' errors

    master

    If the calibration process stops and displays a "Connection issue" message (specifically reported with the MQ-135 in clean air), follow these steps:

    1. Verify physical connections: Check all wiring between the sensor and the microcontroller (Arduino/ESP32) to ensure there is no loose contact or short circuit.
    2. Test with a basic sketch: Run a simple analog read program (without using this library) to confirm the sensor is providing varying voltage levels and is physically functional.
    3. Check air quality: Ensure the sensor is actually being exposed to the expected environment (e.g., clean air for R0 calibration).
  7. Ensure accurate resistance calculation using `setVCC`

    master

    In older versions of the library, sensor resistance was calculated using _VOLT_RESOLUTION instead of the actual supply voltage.

    To ensure accurate readings, use version 3.0.1 or later, which uses the actual VCC in its equations. You can manage the supply voltage using the following methods:

    • setVCC(float voltage): Sets the actual supply voltage.
    • getVCC(): Retrieves the current supply voltage setting.
    // Example of setting the supply voltage for accurate calculations
    sensor.setVCC(5.0);
  8. Get MQUnifiedsensor sensor information

    master

    Use these methods to retrieve the current configuration and calculated values:

    • getA(): Returns coefficient a.
    • getB(): Returns coefficient b.
    • getR0(): Returns the current $R_0$ value.
    • getRL(): Returns the load resistor value.
    • getVCC(): Returns the sensor supply voltage.
    • getVoltResolution(): Returns the voltage resolution.
    • getRegressionMethod(): Returns the current regression method as a String.
    • getVoltage(bool read = true, bool injected = false, int value = 0): Returns the voltage reading.
    • getRS(): Returns the current $R_S$ value.
  9. Configure MQUnifiedsensor parameters

    master

    Use the following methods to configure the sensor's electrical and mathematical parameters before calling init() or update():

    • setVCC(float vcc): Set the sensor supply voltage (default 5.0).
    • setVoltResolution(float voltage_resolution): Set the voltage resolution (default 5.0).
    • setPin(int pin): Set the analog pin number.
    • setADC(int value): Set the ADC value (used primarily for externalADCUpdate).
    • setRL(float RL): Set the load resistor value in KiloOhms (default 10).
    • setR0(float R0): Set the $R_0$ value.
    • setA(float a) and setB(float b): Set the coefficients for the regression model.
    • setRegressionMethod(int regressionMethod): Choose the mathematical model:
      • 1: Exponential
      • 2: Linear
    • serialDebug(bool onSetup): Enable serial output to show sensor information during setup.
  10. Initialize MQUnifiedsensor

    master

    To use the library, instantiate the MQUnifiedsensor class. You can provide the board type (e.g., "Arduino"), the voltage resolution (e.g., 5.0 or 3.3), the ADC bit resolution (e.g., 10 or 12), the analog pin, and the sensor type.

    Available constructors:

    • MQUnifiedsensor(String Placa = "Arduino", float Voltage_Resolution = 5, int ADC_Bit_Resolution = 10, int pin = 1, String type = "CUSTOM MQ")
    • MQUnifiedsensor(String Placa = "Arduino", String type = "CUSTOM MQ")
    // Example initialization for a 3.3V ESP32 with 12-bit ADC on pin 34
    MQUnifiedsensor MQ( "ESP32", 3.3, 12, 34, "MQ2" );
  11. Calibrate and read MQ sensor data

    master

    The library provides methods to calibrate the sensor in clean air and read the concentration in PPM.

    • init(): Initializes the sensor settings.
    • update(): Updates the internal sensor readings.
    • calibrate(float ratioInCleanAir, float correctionFactor = 0.0): Calibrates the sensor using the ratio of $R_S/R_0$ found in clean air.
    • readSensor(bool isMQ303A = false, float correctionFactor = 0.0, bool injected=false): Returns the sensor reading in PPM.
    • readSensorR0Rs(float correctionFactor = 0.0): Returns the $R_0/R_S$ ratio.
    • externalADCUpdate(float volt): Manually update the sensor reading using a provided voltage value (useful for external ADCs).
    MQUnifiedsensor MQ("Arduino", 5, 10, A0, "MQ2");
    
    void setup() {
      MQ.init();
      // Calibrate with a ratio of 10.0 in clean air
      MQ.calibrate(10.0);
    }
    
    void loop() {
      MQ.update();
      float ppm = MQ.readSensor();
      Serial.print("PPM: ");
      Serial.println(ppm);
      delay(1000);
    }