Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
BETTESWORTHConstruction
Construction Technology

IoT Projects Part 9: Gas Detection and Safety Monitoring with ESP32 and MQ-2

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This project builds an educational gas-monitoring prototype around an ESP32, MQ-2 sensor, local LEDs and buzzer, MQTT telemetry, and a PyQt5 desktop dashboard. It is useful for learning embedded sensing and remote monitoring, but it is not a certified residential, construction-site, industrial, smoke, carbon-monoxide, or life-safety alarm.

The original project by The Embedded Things uses an MQ-2 connected to GPIO32, publishes readings to MQTT, and displays gas estimates and sensor voltage on a desktop interface. Reproducing it is straightforward; making it dependable requires additional attention to voltage protection, warm-up, calibration, fault handling, and local fail-safe alarming.

As an Amazon Associate I earn from qualifying purchases.

What the system does

The design has four layers:

  1. Sensing: The MQ-2 changes electrical conductivity when exposed to several combustible gases and smoke.
  2. Local alerting: Green, yellow, and red LEDs show safe, warning, and danger states; the red state also activates a buzzer.
  3. Network telemetry: The ESP32 publishes gas and voltage data through MQTT.
  4. Dashboard monitoring: A PyQt5/PyQtGraph application shows connection status, readings, thresholds, and live plots.

The published project is documented on Hackster.io.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What an MQ-2 can—and cannot—measure

An MQ-2 is a broad-response semiconductor sensor. It is sensitive to LPG, propane, hydrogen, methane, alcohol vapour, smoke, and other combustible vapours. A high reading therefore does not identify which gas is present. Sensor response also varies with temperature, humidity, contamination, ageing, heater condition, and exposure history. See the sensor information from SunFounder and Waveshare.

#1 Best Overall
ACEIRMC 9pcs/Lot Gas Detection Sensor Module MQ-2 MQ-3 MQ-4 MQ-5 MQ-6 MQ-7 MQ-8 MQ-9 MQ-135 Sensor Module Gas Sensor Starter Kit for Arduino Raspberry Pi (9PCS/Lot)
  • MQ-2 gas sensor sensitive material used in the clean air low conductivity tin oxide (SnO2). When there is the environment in which the combustible gas sensor, conductivity sensor with increasing concentration of combustible gases in air increases.
  • Quick response and recovery characteristics
  • The dual signal output (analog output and TTL output)
  • The analog output and increased with the increase of concentration, the higher the concentration higher voltage
  • Has a very high sensitivity to sulfide, benzene vapor, smoke and other harmful gases

The original firmware converts the ESP32 ADC reading with a simple mapping equivalent to:

return map(raw_value, 0, 4095, MIN_PPM, MAX_PPM);

That creates a convenient display value, but it is not a calibrated concentration measurement. MQ-2 response curves are nonlinear and gas-specific. Unless you perform a controlled calibration, label the result estimated sensor index, approximate PPM, or uncalibrated gas-level estimate rather than presenting it as accurate PPM.

Parts and pin assignments

  • ESP32 development board
  • MQ-2 gas-sensor module
  • Green, yellow, and red LEDs with current-limiting resistors
  • Buzzer
  • MQTT broker and a computer running the PyQt5 dashboard
  • Suitable regulated power supply
  • Voltage-divider, level-shifting, or other input protection as required by the exact sensor module and ESP32 board
Component ESP32 connection
MQ-2 analogue output GPIO32
Green LED GPIO12
Yellow LED GPIO14
Red LED GPIO27
Buzzer GPIO13
Grounds Common ESP32 ground

Electrical precautions

Do not assume that an MQ-2 module is directly compatible with every ESP32. Many modules use a 5 V heater supply and can produce an analogue output approaching 5 V. One vendor specification lists 5 V operation and a 0–5 V analogue output; consult the documentation for your particular module, such as the Joy-IT SEN-MQ2-V2.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Verify the ESP32 ADC input limit and configure attenuation correctly.
  • Use a voltage divider or suitable level protection if the sensor output can exceed the ADC limit.
  • Connect all grounds together.
  • Fit a resistor in series with every LED.
  • Use a transistor or dedicated driver for a buzzer that draws more current than the GPIO can safely supply.
  • Keep the heater supply and high-current wiring away from sensitive analogue wiring where practical.

Reproducing the prototype in simulation or on hardware

In a simulator such as Wokwi, reproduce the GPIO assignments and connect the simulated analogue signal to GPIO32. Simulated gas values demonstrate firmware state changes only; they do not model real gas concentration, sensor ageing, warm-up, contamination, or the electrical behaviour of a physical MQ-2.

On hardware, power the sensor according to its module documentation, allow it to stabilise, and verify the ADC voltage before enabling automatic thresholds. Never release combustible gas indoors or test near flames, sparks, heaters, motors, or other ignition sources.

Rank #2
MERICDA MQ-3 Alcohol Vapour Sensor Module, 5V AO + DO Output (2 Pcs)
  • MQ-3 module for alcohol vapour: SnO2 sensing element heated inside a metal mesh cap
  • Analog output AO rises with gas concentration; digital output DO switches at a level you set
  • 5V DC supply, 4-pin 2.54 mm header (VCC / GND / DO / AO), power and signal LEDs
  • Onboard LM393 comparator and threshold potentiometer, so DO can drive a buzzer or LED with no extra code
  • Two modules per pack; needs warm-up and your own calibration - a prototyping module, not a certified detector

Warm-up, burn-in, and calibration

These are different activities:

  1. Warm-up: brings the heater and sensing element to operating condition after power-up.
  2. Baseline establishment: records behaviour in known clean air.
  3. Gas calibration: correlates sensor resistance or output with a known concentration of a specified gas.

Published guidance varies by module and storage history. SunFounder says a sensor stored for a month or more may need 24–48 hours of initial warm-up, while a recently used sensor may need 5–10 minutes. Joy-IT specifies roughly 10–15 minutes at each start and a 48–168-hour initial burn-in. Waveshare describes approximately one minute for an example demonstration. Treat the shortest figure as a demonstration convenience, not a universal accuracy guarantee.

The original project’s ADC-to-PPM mapping does not replace the MQ-series resistance-ratio and gas-specific calibration process described in typical datasheet procedures, including the DFRobot MQ-2 documentation. For a construction prototype, show a clear Starting/Warming state instead of reporting “safe” immediately after reboot.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Alert thresholds need careful interpretation

The project uses configurable thresholds. Its firmware description indicates a warning level of approximately 600 PPM and a danger level above approximately 900 PPM, while the dashboard section shows a warning threshold of 500 PPM. Resolve this inconsistency in your copy and configuration rather than assuming the values are interchangeable.

Neither 500, 600, nor 900 PPM is a universal safety limit. Limits and alarm requirements depend on the gas, exposure duration, ventilation, room, equipment, jurisdiction, and applicable standards. Because the MQ-2 responds to multiple gases and smoke, these example values should be treated as project parameters or relative alarm points—not regulatory thresholds.

A more robust state machine is:

STARTING  - warm-up timer active
READY     - clean-air baseline established
SAFE      - below warning threshold
WARNING   - warning threshold exceeded for N samples
DANGER    - danger threshold exceeded for N samples; latch alarm
FAULT     - invalid, stale, disconnected, or out-of-range sensor data

Use hysteresis so the state does not chatter at a boundary, require several consecutive samples before escalating, and latch a danger alarm until a person acknowledges it locally. MQTT loss should produce a communications fault, not silently disable the local alarm.

Rank #3
9 in 1 MQ Sensor Modules Kit Project Super Starter Kits for Gas Detection
  • Working voltage: DC 5V; With signal output indicator light;
  • With a long service life and reliable stability;Quick response and recovery characteristics;
  • The analog output and increased with the increase of concentration, the higher the concentration higher voltage
  • For harmful gas family, environment detection device, is suitable for the detection of the ammonia, aromatic compounds, sulfide, benzene vapor, smoke and other harmful gas, gas sensitive element concentration range: 10 to 1000ppm provides reference cases.
  • Package Includes: MQ-2 Smoke Sensor,MQ-3 Alcohol Sensor,MQ-4 Methane Sensor,MQ-5 LPG Natural Gas City Gas Sensor,MQ-6 isobutane propane sensor,MQ-7 Carbon Monoxide Sensor Module,MQ-8 hydrogen sensor,MQ-9 Carbon Monoxide Combustible Gas Sensor,MQ-135 air quality detection sensor

Firmware and MQTT behaviour

The published ESP32 firmware includes Wi-Fi retry and reconnection handling, MQTT authentication and reconnection, analogue sampling, a nominal PPM conversion, voltage calculation, LED logic, PWM buzzer output, roughly once-per-second JSON publishing, MQTT-based enable/disable control, and board-status responses.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Topics

Topic Purpose
arduino/gas Gas reading and sensor voltage
mqtt/request Control or status requests
mqtt/response Board status and responses

Example telemetry

{"gas_ppm":450,"voltage":2.15}

The reported control messages include status_request and TurnOFF. The dashboard expects status text resembling Board : ESP32 Status : Connected.

For a longer-running installation, improve the prototype by validating payload length and numeric ranges, adding a device ID and timestamp, publishing sensor state separately from the value, sending a heartbeat and firmware version, and using an MQTT Last Will message for availability. A bounded JSON serializer or fixed buffer is preferable to extensive Arduino String concatenation.

Be especially cautious with a remote disable command. It must not be able to turn off the only danger alarm. Keep the local red indicator and buzzer independent of Wi-Fi, MQTT, the broker, and the desktop computer.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

The PyQt5 dashboard

The dashboard provides remote visibility rather than the primary safety function. Its features include:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
MERICDA MQ-2 Smoke, LPG, Methane Sensor Module, 5V AO + DO Output (2 Pcs)
  • MQ-2 module for smoke, lpg, methane: SnO2 sensing element heated inside a metal mesh cap
  • Analog output AO rises with gas concentration; digital output DO switches at a level you set
  • 5V DC supply, 4-pin 2.54 mm header (VCC / GND / DO / AO), power and signal LEDs
  • Onboard LM393 comparator and threshold potentiometer, so DO can drive a buzzer or LED with no extra code
  • Two modules per pack; needs warm-up and your own calibration - a prototyping module, not a certified detector
  • MQTT connection status
  • Gas-concentration and voltage displays
  • Three visual safety states
  • Live gas and voltage plots
  • Configurable warning and danger thresholds
  • Malformed-JSON error handling
  • Reset and deactivation flow

It should also show stale data, device reboot, MQTT disconnection, sensor warming, and sensor fault as distinct conditions. A dashboard that continues displaying the last valid number without clearly marking it stale can create a dangerous false impression.

Testing checklist

  • Confirm the sensor is wired correctly and the ADC input is protected.
  • Observe clean-air behaviour after the required warm-up.
  • Test each LED and the buzzer independently.
  • Disconnect Wi-Fi and verify that local alarming still works.
  • Stop the MQTT broker and confirm the device reports a communications fault.
  • Send malformed JSON and out-of-range values to test dashboard handling.
  • Disconnect the sensor and test the fault state.
  • Reboot during a simulated danger condition.
  • Test readings near thresholds for chatter and verify hysteresis.
  • Test power interruption and recovery.

Do not use uncontrolled combustible-gas releases as a casual indoor test. Use safe, controlled methods appropriate to the sensor and environment, and keep all demonstrations away from ignition sources.

Known limitations and failure modes

Expect drift, cross-sensitivity to alcohol vapour, solvents, smoke, and cleaning products, slow recovery after exposure, heater failure, saturation, condensation, contamination, and readings that remain stuck. Sensor documentation also warns that corrosive gases, water exposure, freezing, and excessive exposure can change or damage sensitivity; see the Olimex MQ-2 documentation.

Software can fail through Wi-Fi loss, broker outage, authentication errors, dashboard crashes, malformed payloads, ESP32 resets, or stale data. Hardware can fail through power loss, inadequate buzzer volume, incorrect sensor placement, or unsafe enclosure design. Do not install this unclassified hobby hardware in a hazardous location where certification is required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

MQ-2 alternatives

For experimentation, an MQ-5 may be a better candidate for LPG or natural-gas-focused work, while an MQ-6 is more LPG-oriented. Dedicated electrochemical or infrared sensors are more appropriate when selectivity, repeatability, or calibrated concentration matters. A certified commercial gas alarm is the correct choice for actual residential or occupational life-safety protection. A vendor comparison of MQ-family devices is available from Waveshare.

What this project is—and is not

This is a useful ESP32 learning project and a reasonable prototype for demonstrating analogue sensing, local indicators, MQTT messaging, and desktop visualisation. It is not a gas-identification instrument, calibrated PPM analyser, industrial safety system, hazardous-area device, or replacement for a certified gas, smoke, or carbon-monoxide alarm.

Quick Recap

Bestseller No. 1
Bestseller No. 2
MERICDA MQ-3 Alcohol Vapour Sensor Module, 5V AO + DO Output (2 Pcs)
MERICDA MQ-3 Alcohol Vapour Sensor Module, 5V AO + DO Output (2 Pcs)
MQ-3 module for alcohol vapour: SnO2 sensing element heated inside a metal mesh cap; 5V DC supply, 4-pin 2.54 mm header (VCC / GND / DO / AO), power and signal LEDs
$7.99
Bestseller No. 3
9 in 1 MQ Sensor Modules Kit Project Super Starter Kits for Gas Detection
9 in 1 MQ Sensor Modules Kit Project Super Starter Kits for Gas Detection
Working voltage: DC 5V; With signal output indicator light;
$18.99
Bestseller No. 4
MERICDA MQ-2 Smoke, LPG, Methane Sensor Module, 5V AO + DO Output (2 Pcs)
MERICDA MQ-2 Smoke, LPG, Methane Sensor Module, 5V AO + DO Output (2 Pcs)
MQ-2 module for smoke, lpg, methane: SnO2 sensing element heated inside a metal mesh cap; 5V DC supply, 4-pin 2.54 mm header (VCC / GND / DO / AO), power and signal LEDs
$7.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.