Gas and Smoke with MQ-2
Gas and Smoke with MQ-2
Overview
Section titled “Overview”The MQ-2 is one of the cheapest ways to sense gas, but its “good at qualitative, weak at quantitative” nature is widely misunderstood: the raw value a module gives you is not a concentration, and wiring it straight into an alarm is how problems happen. By the end of this section you will be able to:
- Separate the roles of the analogue and digital outputs and design product logic around them
- Deal with the two unavoidable costs: heater power and warm-up time
- Fit ppm from the Rs/R0 ratio and the sensitivity curve, knowing that you produced an estimate
- Judge clearly where MQ parts must not be used — safety and fire detection are not among their permitted roles
Prerequisites
Section titled “Prerequisites”Before starting this section, make sure you:
- Completed Section 3 of Chapter 25 (dividers and ADC conversion)
- Have an MQ-2 module (4 pins: VCC/GND/DO/AO, or a 6-pin dual-probe MQ-2/MQ-5 board)
- Have a lighter for trigger testing (release gas only — do not ignite it)
Key Concepts
Section titled “Key Concepts”It works on a heated metal-oxide semiconductor
Section titled “It works on a heated metal-oxide semiconductor”The sensing element is a tin-oxide (SnO₂) film operating at several hundred degrees. In clean air, adsorbed oxygen raises the film resistance; reducing gases and smoke consume that oxygen and resistance falls. Consequently:
- The heater must be powered: typically around 5 V and tens to over a hundred milliamps (use your exact part’s datasheet). This is not a device you can run for months on a battery.
- The measured quantity is resistance: the board forms a divider between the sensing element and an on-board load resistor, and AO taps the midpoint voltage.
- Warm-up is mandatory: readings during the first tens of minutes to hours after a cold start are meaningless. Fresh parts should be energised for 24 h or more before taking a baseline; the same applies after long storage.
Two outputs, two jobs
Section titled “Two outputs, two jobs”| Output | What it is | Use it for | Common misuse |
|---|---|---|---|
| AO (analogue) | Voltage that varies continuously with concentration | Trends, threshold curves, self-learned baseline | Reporting it to the customer as ppm |
| DO (digital) | Comparator against a trimmer-set threshold | Simple exceeded/not-exceeded, or an interrupt wake-up | Assuming the threshold can be set remotely (the trimmer is manual) |
Standard product architecture: AO is the measurement, DO is the hard floor. Connect both, and the wiring sheet reads “1 ADC plus 1 GPIO”. Using DO alone means accepting two consequences: the threshold can only be moved with a screwdriver on site, and temperature drift moves the threshold.
Voltage range and dividing: the second 5 V trap
Section titled “Voltage range and dividing: the second 5 V trap”MQ-2 modules are normally powered at 5 V, and the AO swing follows that rail — at high concentrations it can exceed 3.3 V, which overruns an ESP32 ADC input and parks it in the clamping region. Three engineering options:
- Resistive divider into the ADC: e.g. 3.3 kΩ upper plus 1.5 kΩ lower maps a 5 V full swing to about 2.3 V with margin. The price is a higher source impedance — add 100 nF at the ADC pin and sample more slowly.
- Power the module from 3.3 V: works on some boards, but the heater was designed for 5 V, so sensitivity and response time change and everything must be recalibrated.
- Use an external ADC (ADS1115): better range and resolution, at the cost of a part and an I2C bus slot.
Write the divider ratio into the wiring sheet and into the conversion code. Otherwise readings drift with module batch, and nobody tracing the fault knows this stage exists.
From reading to ppm: a fitted estimate
Section titled “From reading to ppm: a fitted estimate”The usual three steps:
-
Compute the sensor resistance Rs from the AO voltage
Vout, the module supplyVCCand the on-board load resistorRL:Rs = RL × (VCC − Vout) / Vout // invert the expression if the sensor is in the lower leg — confirm topology first -
Compute Rs/R0, where
R0is Rs under clean-air calibration. Practically: take a stable clean-air reading and back outR0 = Rs_clean / K, whereKis the clean-air ratio given by the datasheet. Take K from the datasheet of your exact part and batch — do not copy an internet figure. -
Fit concentration from the sensitivity curve, which is roughly straight in log-log coordinates:
ppm = A × (Rs / R0) ^ BAandBcome from two points on the curve, and each target gas (LPG, propane, hydrogen, smoke) has its own pair:B = log(ppm1 / ppm2) / log((Rs/R0)1 / (Rs/R0)2)A = ppm1 / pow((Rs/R0)1, B)
What these three steps produce is an estimate, modulated by humidity, temperature, airflow, ageing and cross-gases. To state a contractual figure you must calibrate against reference gas in the target environment, at two or more points, and attach the calibration record to the acceptance document.
Cross-sensitivity: it cannot tell what you are burning
Section titled “Cross-sensitivity: it cannot tell what you are burning”The MQ-2 responds to LPG, propane, hydrogen and smoke, and is also triggered by alcohol and ammonia. It can answer “there is a reducing gas or smoke in the air and levels are rising”; it cannot answer “is this a natural-gas leak”. Distinguishing gas types requires a sensor array plus discrimination algorithms, or dedicated electrochemical/NDIR parts.
It is not a safety alarm device
Section titled “It is not a safety alarm device”This is the most important sentence in the section: MQ series parts carry no fire or gas-safety certification and cannot be relied on for personal safety alarm functions. They are appropriate for informational monitoring, process early warning and teaching demos. The moment your product is positioned as a gas-leak alarm or smoke detector, you must select certified components and a certified overall design, and go through the corresponding approval process.
The technical reasons are concrete: sensitivity drifts with age, continuous heating is required, behaviour in cold or very humid conditions is unstable, and condensation contaminates the sensing film. Putting that uncertainty inside a life-safety chain is not defensible.
Implementation
Section titled “Implementation”Read AO voltage, compute Rs and relative trend
Section titled “Read AO voltage, compute Rs and relative trend”const uint8_t AO_PIN = 35; // ADC1const uint8_t DO_PIN = 26;
// Front-end divider (3.3 kΩ upper, 1.5 kΩ lower): scale the ADC reading back to module AO voltageconst float DIVIDER_RATIO = 1.5f / (3.3f + 1.5f);const float VCC_MODULE = 4.95f; // measured module VCC, not the nominal 5.00const float R_LOAD = 1000.0f; // on-board load resistor — measure it, do not assume
float readAoVolts() { uint32_t raw = 0; for (uint8_t i = 0; i < 9; i++) { raw += analogRead(AO_PIN); delay(2); } float vAdc = (raw / 9.0f) * 3.1f / 4095.0f; // 11 dB range, full scale taken from measurement return vAdc / DIVIDER_RATIO;}
float readRs() { float v = readAoVolts(); if (v < 0.02f || v > VCC_MODULE - 0.02f) return -1; // endpoints are invalid return R_LOAD * (VCC_MODULE - v) / v; // sensor in the upper leg}
void setup() { Serial.begin(115200); pinMode(DO_PIN, INPUT_PULLUP);}
void loop() { float rs = readRs(); Serial.printf("AO=%.2f V Rs=%.0f ohm DO=%d\n", readAoVolts(), rs, digitalRead(DO_PIN)); delay(2000);}Clean-air self-calibration of R0 (once per warm-up)
Section titled “Clean-air self-calibration of R0 (once per warm-up)”float calibrateR0(float K) { // K: clean-air Rs/R0 ratio from YOUR datasheet float sum = 0; uint8_t n = 0; for (uint8_t i = 0; i < 10; i++) { float rs = readRs(); if (rs > 0) { sum += rs; n++; } delay(2000); } if (n < 8) return -1; // too few valid samples: redo the calibration return (sum / n) / K;}Fitted concentration (coefficients derived from two curve points)
Section titled “Fitted concentration (coefficients derived from two curve points)”float estimatePpm(float rs, float r0, float A, float B) { if (rs <= 0 || r0 <= 0) return -1; return A * pow(rs / r0, B);}Compute A and B yourself from two points on the datasheet curve, put them in a comment together with which chart and which date they came from — traceable fit coefficients are the minimum bar for gas projects.
Verification
Section titled “Verification”Functional and stability checks
Section titled “Functional and stability checks”| Check | Expected result | Verified |
|---|---|---|
| Reading immediately after power-on | Clearly high and unstable (warm-up incomplete; alarms must be suppressed) | |
| After 24 h continuous power | Stable in clean air, R0 baseline can be captured | |
| Lighter gas released nearby (no flame) | Rs drops quickly, AO rises; slow recovery when removed | |
| Normal ventilation, no odour | Reading sits around baseline | |
| Humid environment (bathroom doorway, 10 min) | Reading shifts up and recovery takes time — record the drift band | |
| Turning the DO trimmer | Trigger point moves continuously and can be positioned | |
| Measured ADC pin voltage | Never exceeds ~3.1 V (confirms divider ratio matches code) |
Two confirmations you must do
Section titled “Two confirmations you must do”- Measure
R_LOAD: with power off, measure resistance between AO and GND. Silkscreen and reality differ, and this value goes straight into the Rs formula. - Confirm the topology: boards may place the sensing element and the load resistor either side of the tap, which inverts the Rs expression. Measure AO in clean air and again with target gas present, use the direction to identify the topology, then commit to a formula.
Troubleshooting
Section titled “Troubleshooting”Issue 1: alarm right after power-on, resolves itself hours later
Section titled “Issue 1: alarm right after power-on, resolves itself hours later”Symptoms: false alarm on new installation or after a power cut.
Cause: incomplete warm-up. Rs is elevated until the heater stabilises, so an old R0 yields a high computed concentration.
Solutions:
- Add a warm-up quiet period in firmware (24 h for first power-on, 15–30 min for short restarts); log only, do not alarm
- Report a
warmingstatus rather than painting “0 ppm” or reusing the last value on the dashboard - If a product must go live fast, run ageing and pre-calibration at the factory
Issue 2: AO pinned high or completely dead
Section titled “Issue 2: AO pinned high or completely dead”Symptoms: ADC reads near the ceiling constantly, or nothing happens when gas is present.
Possible causes:
- Divider ratio wrong, so the real AO voltage exceeds ADC range and clamps
- Wrong load-resistor value, scaling Rs up or down
- Failed sensing element (long exposure to high concentrations, moisture, or extended storage)
Solutions:
- Measure AO-to-GND with a multimeter and compare with the code value — this separates front-end range problems from conversion bugs
- Measure the load resistor with power off
- Swap in a fresh module under identical conditions to separate part ageing from circuit issues
Issue 3: the digital output trips constantly
Section titled “Issue 3: the digital output trips constantly”Symptoms: cooking, alcohol spraying, perfume nearby all trigger it.
Cause: cross-sensitivity plus a low threshold — that is physics, not a defect.
Solutions:
- Move the installation away from stoves, doorways and cleaning-product areas; face the inlet towards where target gas would arrive
- Raise the threshold and require N consecutive exceedances before alarming (3 × 2 s is a reasonable starting point)
- If discrimination is genuinely needed, change architecture instead of fighting it with thresholds
Issue 4: baseline drifts slowly with the seasons
Section titled “Issue 4: baseline drifts slowly with the seasons”Symptoms: same location, noticeably different baseline in summer and winter.
Cause: humidity and temperature alter oxygen adsorption, and heater dissipation also changes with ambient temperature.
Solutions:
- Log temperature and humidity alongside, and apply a banded correction or lookup table in firmware — and state in the documentation that this is empirical compensation
- Establish periodic self-calibration: retake the baseline during known-clean periods, keeping calibration history
- Document the baseline-management strategy so drift is not read as a broken sensor
Best Practices
Section titled “Best Practices”- Do: connect AO and DO together — AO quantifies, DO provides the hard floor
- Do: surface warm-up and calibration failure as statuses that never participate in alarm decisions
- Do: centralise the six parameters
VCC, divider ratio,R_LOAD,K,A,B, each annotated with its source and measurement date - Do: drop MQ parts entirely when the product needs battery or low power — choose a low-power electrochemical or solid-state sensor and redo the power budget
- Don’t: use MQ series for fire or gas-leak safety alarm functions
- Don’t: quote a fitted ppm as a calibrated measurement
- Don’t: seal the module inside a closed enclosure; without airflow the response slows by an order of magnitude
Summary
Section titled “Summary”Key points of this section:
- MQ-2 is a heated SnO₂ device: it needs heater power and warm-up, and is unsuitable for long-term battery operation
- AO quantifies, DO bounds: connect both so the product can show trends and still hold a floor
- The 5 V swing is the second ADC trap: divide it down, write the ratio into code, and verify by measurement
- ppm is a fit, not a measurement: Rs → Rs/R0 → log-log straight line, with coefficients from your own batch’s datasheet and traceable provenance
- Cross-sensitivity and ageing disqualify it as a safety device: informational monitoring yes, fire or gas safety no — that requires certified purpose-built parts
Next section: HC-SR04 ultrasonic ranging — dead zone, missing echoes and the 5 V Echo constraint.
We provide ESP32 ODM design-to-manufacturing services. From prototype to production — the team behind this tutorial can build it with you.
💡 Mention tutorial.imagrove.com in your Alibaba chat with us — get 10% off your custom project quote.
First published attutorial.imagrove.com/sensor-module-selection/06-gas-and-smoke-with-mq-2/Please credit Imagrove and link back to this page when quoting or republishing.
Questions or issues with this tutorial?
Sign in with GitHub to leave a comment. If a step fails for you, tell us — we verify it and update the tutorial.
© Imagrove · ESP32 IoT Tutorial