Fall ResetAmazon USFall reset deals: check better picks before checkoutAmazon US: today's deals, useful picks and quick comparisons.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCFall ResetAmazon USWork and home upgrades are worth comparing todayAmazon US: today's deals, useful picks and quick comparisons.See Picks×
Skip to content
Blog

DIY Gas Sensor Project with ESP32: Build an MQ-2 Smoke and Gas Trend Monitor

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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

An ESP32 can read an MQ-2 sensor and trigger a local warning when its reading rises above a learned clean-air baseline. The safest way to build this project is to treat it as an educational smoke-and-gas trend monitor—not as a certified smoke alarm, carbon-monoxide alarm, fire alarm, or combustible-gas detector.

The MQ-2 responds to smoke and several vapours and gases, including LPG, methane, propane, hydrogen, alcohol vapour and potentially carbon monoxide. That broad response is useful for experiments and workshop monitoring, but it cannot identify the hazard or prove that a particular safety limit has been exceeded.

Important: Install certified smoke and CO alarms independently. Smoke alarms are covered by requirements such as UL 217, while CO alarms are addressed separately under standards such as UL 2034. This homemade circuit has not been evaluated to those requirements.

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

What this ESP32 MQ-2 project actually detects

The MQ-2 is a heated tin-oxide semiconductor sensor. Its electrical conductivity changes when exposed to smoke and various combustible gases. The ESP32 measures the module’s analogue output and looks for a sustained change from normal conditions.

#1 Best Overall
ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA Compatible with Arduino IDE (3PCS)
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Support LWIP protocol, Freertos
  • SupportThree Modes: AP, STA, and AP+STA
  • Ultra-Low power consumption, Compatible with Arduino IDE
  • ESP32 is a safe, reliable, and scalable to a variety of applications

That means the project detects sensor response, not a uniquely identified substance. Cooking fumes, alcohol vapour, solvents, dust and other contaminants can also change the reading. Product documentation describes an approximate flammable-gas range of 300–10,000 ppm, but that is not an accurate smoke-concentration measurement or a universal alarm threshold. See the MQ-2 product information for the manufacturer’s stated range and target gases.

Why use an ESP32?

An ESP32 provides an analogue input for the sensor, GPIO pins for an LED or buzzer, and Wi-Fi or Bluetooth for optional logging and notifications. The original ESP32 includes 12-bit SAR ADC hardware, but ADC behaviour and pin availability differ between original ESP32, ESP32-S2, ESP32-S3, ESP32-C3 and other variants. Confirm the pin map and ADC guidance for your exact development board in the Espressif documentation.

Parts required

  • ESP32 development board and USB cable
  • MQ-2 sensor or MQ-2 module
  • Suitable regulated 5 V supply for the MQ-2 heater
  • 10 kΩ and 20 kΩ resistors for an analogue voltage divider
  • Breadboard and jumper wires
  • Optional LED and 220–330 Ω resistor
  • Optional active buzzer; use a transistor driver if its current exceeds the GPIO’s safe capability
  • Optional pushbutton for recalibrating the clean-air baseline

A conventional MQ-2 breakout can draw approximately 150 mA and is commonly specified for 5 V. Do not assume that a small ESP32 regulator or USB source can power every module reliably. The SparkFun breakout information gives representative supply and current details, but clones may differ.

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

Protect the ESP32 analogue input

Many MQ-2 modules are powered from 5 V and can produce an analogue output approaching several volts. An ESP32 input is not 5-V tolerant. Never connect AO directly to an ESP32 ADC pin without checking the module output and adding appropriate protection.

Rank #2
ELEGOO 3PCS ESP-32 Dev Boards, ESP-WROOM-32, USB-C, WiFi Bluetooth 4.2
  • Dual-Core Performance Up to 240 MHz: Run sensor processing, wireless communication, automation logic and connected-device tasks on a 32-bit dual-core ESP32 platform designed for responsive embedded and IoT projects
  • Built-in Wi-Fi and Bluetooth 4.2: Connect to 2.4 GHz Wi-Fi networks or use Bluetooth Classic and BLE for wireless sensors, smart devices, remote controls, home automation and other connected projects
  • Flexible Power-Saving Modes: ESP32 power-management features support dynamic clock scaling and low-power operating modes, helping developers reduce energy use in compatible sensing, monitoring and connected-device applications, suitable for battery-powered Internet of Things (IoT) devices.
  • USB-C Programming with CP2102: Connect through USB-C for power, sketch uploads and serial monitoring, while GPIO, UART, SPI and I2C interfaces support sensors, displays, motor drivers and other modules (USB-C cable not included)
  • Over-the-Air Update Support: Configure OTA functionality through a compatible ESP-32 software framework to update deployed firmware over Wi-Fi without reconnecting the board by USB for every revision

Use this divider:

MQ-2 AO ---- R1 10 kΩ ----+---- ESP32 GPIO36 / ADC input
                           |
                         R2 20 kΩ
                           |
                          GND

The divider produces:

VADC = VAO × R2 / (R1 + R2)
VADC = VAO × 20 kΩ / 30 kΩ
VADC ≈ 0.667 × VAO

A 4.0 V sensor output therefore becomes approximately 2.67 V at the ESP32. Check the maximum output and ADC requirements for your particular module and board before powering the circuit.

Wiring

MQ-2 connection ESP32/project connection
VCC Suitable 5 V rail
GND Common project ground
AO Through the 10 kΩ/20 kΩ divider to GPIO36
DO Optional only; verify its voltage before connecting

GPIO36 is input-only and is suitable for analogue measurement on the classic ESP32. Other ESP32 families may use different ADC pins. The ESP32 and MQ-2 supply must share a ground. Powering the heater from 3.3 V may cause weak sensitivity, slow warm-up or unstable readings.

The module’s DO pin is produced by a comparator. Its potentiometer adjusts the comparator’s switching point; it does not calibrate the sensor in ppm. For this project, AO is the better choice because it preserves the changing signal for filtering, graphing and baseline comparison.

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

Warm-up and clean-air calibration

The MQ-2 has a heated sensing element, so its output changes while it warms. Some breakout instructions use approximately 20 seconds for an initial demonstration, but that should not be treated as universal stabilisation time. A more useful prototype baseline takes readings over 30–120 seconds in clean, well-ventilated air.

Rank #3
ELEGOO ESP-32 Super Starter Kit with Tutorial Compatible with Arduino IDE
  • Powerful ESP-32 Board: Unlock the world of Internet of Things (IoT) and advanced electronics with the heart of this kit: the ESP-32 board. It features a powerful dual-core processor, integrated Wi-Fi and Bluetooth 4.2, making it perfect for building connected, smart devices that communicate with your phone or the cloud. It's fully compatible with the Arduino IDE for easy programming.
  • Super Starter Kit: This kit contains over 35 different modules and electronic components, including sensors, displays, motors, and input devices. From LEDs and buttons to an OLED screen, servo motor, and keypad, you have everything needed to explore a vast range of projects in one box.
  • Step by Step Online Tutorial: Jump right in with our detailed, beginner-friendly tutorial. Access 30+ projects with complete code, clear circuit diagrams, and step-by-step instructions. Learn the fundamentals of electronics, coding, and how to utilize the ESP-32's unique capabilities without any prior experience.
  • Hands-on Learning for All Skill Levels: Perfect for students, makers, engineers, and hobbyists. Start with basic circuits and coding, then progress to intermediate and advanced IoT applications. Build practical projects like weather stations, smart home controllers, remote-controlled devices, and interactive gadgets. The skills you learn are the foundation for real-world innovation.
  • Quality & Great Support: Elegoo is committed to quality. We provide a clear, detailed tutorial guide, refined code, and a well-organized component kit. All modules are carefully selected for reliability and ease of use. Our dedicated technical support team and active online community are ready to help you succeed in your learning journey.
  1. Place the sensor in clean air away from solvents, cooking fumes and combustion sources.
  2. Power the heater and discard the initial readings.
  3. Collect several hundred filtered readings.
  4. Calculate an average or, preferably, a median baseline.
  5. Set separate alarm-on and alarm-off thresholds.
  6. Recalibrate after relocating the device, changing ventilation or leaving it switched off for a long period.

Temperature, humidity, airflow, supply voltage, sensor age and contamination can all affect the result. A single startup reading is not a reliable definition of normal air.

Arduino IDE example

This example uses AO through the divider and GPIO36 on a classic ESP32. It reports raw ADC-scale values and relative change rather than pretending to calculate accurate ppm.

#include <Arduino.h>

constexpr int MQ2_PIN = 36;
constexpr int LED_PIN = 2;
constexpr int BUZZER_PIN = 25;
constexpr int SAMPLE_COUNT = 200;
constexpr unsigned long SAMPLE_INTERVAL_MS = 50;

float baseline = 0.0f;
float alarmOnThreshold = 0.0f;
float alarmOffThreshold = 0.0f;

float readFilteredValue() {
  long total = 0;
  for (int i = 0; i < 10; i++) {
    total += analogRead(MQ2_PIN);
    delay(5);
  }
  return total / 10.0f;
}

void establishBaseline() {
  Serial.println("Keep the sensor in clean air...");
  delay(30000);

  double total = 0;
  for (int i = 0; i < SAMPLE_COUNT; i++) {
    total += readFilteredValue();
    delay(SAMPLE_INTERVAL_MS);
  }

  baseline = total / SAMPLE_COUNT;
  alarmOnThreshold = baseline * 1.35f;
  alarmOffThreshold = baseline * 1.20f;

  Serial.print("Baseline: ");
  Serial.println(baseline);
  Serial.print("Alarm ON threshold: ");
  Serial.println(alarmOnThreshold);
  Serial.print("Alarm OFF threshold: ");
  Serial.println(alarmOffThreshold);
}

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);
  digitalWrite(BUZZER_PIN, LOW);

  analogReadResolution(12);
  analogSetAttenuation(ADC_11db);
  establishBaseline();
}

void loop() {
  static bool alarmActive = false;
  static unsigned long lastPrint = 0;
  float reading = readFilteredValue();

  if (!alarmActive && reading >= alarmOnThreshold) {
    alarmActive = true;
  }
  if (alarmActive && reading <= alarmOffThreshold) {
    alarmActive = false;
  }

  digitalWrite(LED_PIN, alarmActive ? HIGH : LOW);
  digitalWrite(BUZZER_PIN, alarmActive ? HIGH : LOW);

  if (millis() - lastPrint >= 1000) {
    lastPrint = millis();
    Serial.print("Reading: ");
    Serial.print(reading);
    Serial.print(" | Baseline: ");
    Serial.print(baseline);
    Serial.print(" | Status: ");
    Serial.println(alarmActive ? "ALARM" : "normal");
  }
  delay(100);
}

The 1.35 and 1.20 multipliers are starting points for experimentation, not safety limits. Actual values depend on the sensor, module, ADC configuration and environment.

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.

Use persistence and hysteresis

A single high ADC sample can be electrical noise or a brief disturbance. A practical prototype should combine filtering with persistence:

Rank #4
ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA Compatible with Arduino IDE (1 PCS)
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Support LWIP protocol, Freertos;ESP32 is a safe, reliable, and scalable to a variety of applications
  • SupportThree Modes: AP, STA, and AP+STA
  • Ultra-Low power consumption, Compatible with Arduino IDE
  • 1PCS 30Pin ESP32 Development Board 2.4GHz WiFi Dual Cores Microcontroller Integrated with Antenna RF Low Noise Amplifiers Filters
if filtered_reading > alarm_on_threshold for 3 seconds:
    activate alarm

if filtered_reading < alarm_off_threshold for 10 seconds:
    clear alarm

Using different ON and OFF thresholds prevents the alarm from chattering when the reading hovers around one boundary. The time values are tunable engineering choices, not certified response times. A rate-of-rise check can also help identify a rapidly changing condition, but it does not make the sensor selective or safety-certified.

Why not convert the ADC value directly to ppm?

A formula such as ppm = ADC reading × constant is not credible for this sensor. A gas-specific estimate requires the exact sensor variant, load resistance, heater conditions, sensor resistance, a clean-air reference commonly called R0, a gas-specific response curve and controlled calibration concentrations. Temperature and humidity characterisation may also be needed.

For a smoke-and-gas trend monitor, use relative change, baseline deviation and time history. Do not label arbitrary ADC values as ppm.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Safe testing

Test the LED and buzzer by temporarily lowering the software threshold before exposing the sensor to anything. Do not release LPG, generate carbon monoxide, burn plastics or use an uncontrolled flame for calibration.

Best Value
HiLetgo ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA for Arduino IDE
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Ultra-Low power consumption, works perfectly with the Arduino IDE
  • Support LWIP protocol, Freertos
  • SupportThree Modes: AP, STA, and AP+STA
  • ESP32 is a safe, reliable, and scalable to a variety of applications

If you demonstrate response to smoke, use only a very small amount of incense in a controlled, ventilated setting, keep combustible materials away from the warm sensor and wiring, and never treat the result as a safety test. The heater itself becomes warm.

Troubleshooting

Symptom Likely cause Remedy
ADC value stays at zero Wrong pin, missing ground or wiring error Confirm the ADC pin, divider connections and common ground.
ESP32 resets MQ-2 current demand or an inadequate 5 V rail Use a suitable regulated supply and retain a shared ground.
Reading is saturated AO is too high or the sensor is exposed to strong vapour Check the divider with a meter and remove the exposure.
Reading drifts for minutes Heater warm-up or changing airflow Extend warm-up and establish a new baseline.
DO works but AO does not AO or divider wiring fault Measure both AO and the divider output independently.
Alarm chatters No hysteresis or excessive noise Add filtering, persistence and separate ON/OFF thresholds.
Reading changes near alcohol or cleaner MQ-2 cross-sensitivity Treat this as expected sensor behaviour, not proof of smoke.
Wi-Fi notification fails Network outage or blocking firmware Keep a local alarm, add connection timeouts and implement reconnection.

Useful upgrades

  • Add an OLED showing the current reading, baseline and alarm state.
  • Log readings with timestamps to an SD card or MQTT dashboard.
  • Add temperature and humidity measurements to explain environmental drift.
  • Use a watchdog, heartbeat LED and sensor-disconnection fault state.
  • Add battery-voltage monitoring and a local power-failure indicator.
  • Drive relays, fans and larger buzzers through a transistor or MOSFET with suitable protection; do not drive inductive loads directly from an ESP32 GPIO.
  • Monitor the approved auxiliary or test signal of a certified alarm rather than replacing its sensing circuitry.

MQ-2 alternatives

For LPG or methane trend experiments, MQ-5 or MQ-6 may be more appropriate starting points, although they remain heated, cross-sensitive sensors requiring calibration. For airborne-particle or wildfire-smoke logging, an optical particulate sensor is conceptually closer to measuring smoke particles. VOC, particulate, temperature and humidity sensors can complement one another, but none automatically becomes a certified fire-detection system.

Final safety boundary

This project can teach analogue measurement, filtering, embedded programming and Wi-Fi alerting. It can provide a useful supplemental indication that the air around a workshop or construction project has changed. It cannot reliably distinguish smoke from gas or vapour, measure a certified hazard concentration, guarantee detection during a fire, or replace listed alarms.

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.

For real protection, install certified smoke alarms and dedicated certified CO alarms appropriate to the building. The U.S. EPA’s CO guidance also stresses that CO alarms supplement—not replace—proper installation and maintenance of fuel-burning appliances.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
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.