Build Project

Smart City

ESP32 MQ-2 Threshold Demonstration

Build a bounded MQ-2 bench demonstration: 5 V heater, 12k/10k ADC divider, conditioning, relative thresholds and explicit safety limitations.

IntermediateAges 13+Assembly varies; initial sensor conditioning is separate (48+ hours)Under 25 USDParent Safe
Illustrative MQ-2 project scene; use the logical wiring diagram for the supported bare-sensor circuit
Project Mission

Build an MQ-2 Threshold Demonstration

The Story

Follow one documented electrical circuit before interpreting changing numbers. This page does not establish gas concentration, AQI, clean-air safety, smoke detection or successful hardware operation.

Explain Like I'm 12

The heated sensing material changes resistance. A resistor turns that change into a voltage; a second network reduces the voltage before the ESP32 reads it. Many gases and environmental changes can affect the same reading.

Learning Support

  • Recommended ageAges 13+
  • Adult supervisionAdult supervision required for sensor warmup, buzzer noise, and safe non-flame bench testing.
  • Classroom useUse as a sensor-threshold and safety-boundary discussion, not as a life-safety demonstration.
  • Parent promptAsk what makes this different from a certified smoke detector.
  • Screen-free activityDraw disarmed, armed-below-threshold and armed-above-threshold states; none means safe air.
  • Next challengeAdd an OLED that shows raw sensor readings before adding any network notification.
  • Skills practiced
    • ADC1 input
    • Qualified voltage interface
    • Relative thresholds
    • Safety limitations
  • Learning outcomes
    • Separate heater power from 3.3 V GPIO signals.
    • Read a divided analog voltage on ADC1 GPIO34.
    • Distinguish initial conditioning, power-up warm-up and observed baseline stability.
    • Use manually armed relative-count thresholds without claiming calibration.
  • Mini experiments
    • Observe raw counts without creating smoke or releasing gas.
    • Compare startup and manual arming states.

Safety Standards

  • Only the documented low-voltage circuit is supported. No mains wiring or life-safety function is covered.
  • Disconnect USB and every external supply before rewiring; check actual voltage and terminal labels before attaching a GPIO.
  • Review the selected parts and supply budget. Documentation review and calculated limits are not physical hardware validation.

What You Will Build

A manually armed MQ-2 relative-reading demonstration on a classic ESP32-WROOM DevKit. It uses the bare six-pin Winsen sensor, not an unidentified AOUT/DOUT breakout. GPIO25/GPIO26 LEDs and a transistor-switched buzzer show the threshold state.

Learning Objectives

  • Separate heater power from 3.3 V GPIO signals.
  • Read a divided analog voltage on ADC1 GPIO34.
  • Distinguish initial conditioning, power-up warm-up and observed baseline stability.
  • Use manually armed relative-count thresholds without claiming calibration.

Components List

  • Classic ESP32-WROOM DevKitUSB-powered; Arduino-ESP32 3.3.2 review baseline. Not an S3/C3 pin map.
  • Bare Winsen MQ-2 six-pin sensorIdentify the H heater pair and A/B electrode pairs using the manufacturer lead-view drawing before wiring; no module DOUT is used.
  • Regulated 5.0 V ±0.1 V external supply, at least 500 mAHeater and sensing-loop supply only; never ESP32 VIN/USB. The 950 mW heater rating corresponds to about 190 mA at 5 V; allow startup margin.
  • 10 kΩ load resistor RL; 12 kΩ and 10 kΩ divider resistorsDivider resistors must be 1%; RL is separate from the 10 kΩ divider leg.
  • 100 nF ceramic capacitorAt GPIO34 to common GND; filtering does not replace the divider.
  • Red and green LEDs, each with its own 1 kΩ resistorGPIO25 red; GPIO26 green. Green means below the chosen relative threshold, never safe air.
  • Joy-IT COM-KY012APB active piezo buzzerMay 2024 manual: sound from voltage between S and minus; centre terminal unused. This is not a generic three-pin logic-input module. Use the separate regulated 4.5 V rail, not the heater rail or a GPIO; manufacturer current maximum is 30 mA.
  • onsemi P2N2222A TO-92, 330 Ω (1%) and 100 kΩ resistorsExact transistor: pin 1 collector, 2 base, 3 emitter; use the datasheet package view. GPIO27 controls the base, never powers the buzzer.
  • Separate regulated 4.5 V ±5% output rail, at least 200 mAA separate bench supply output powers the selected relay/buzzer inside its documented 3–5 V range. Its GND joins common GND; positive remains off ESP32 power pins and off the 5 V heater rail.

Bill of Materials

PartQtyEstimated CostNotes
Classic ESP32-WROOM DevKitAs listedVariesUSB-powered; Arduino-ESP32 3.3.2 review baseline. Not an S3/C3 pin map.
Bare Winsen MQ-2 six-pin sensorAs listedVariesIdentify the H heater pair and A/B electrode pairs using the manufacturer lead-view drawing before wiring; no module DOUT is used.
Regulated 5.0 V ±0.1 V external supply, at least 500 mAAs listedVariesHeater and sensing-loop supply only; never ESP32 VIN/USB. The 950 mW heater rating corresponds to about 190 mA at 5 V; allow startup margin.
10 kΩ load resistor RL; 12 kΩ and 10 kΩ divider resistorsAs listedVariesDivider resistors must be 1%; RL is separate from the 10 kΩ divider leg.
100 nF ceramic capacitorAs listedVariesAt GPIO34 to common GND; filtering does not replace the divider.
Red and green LEDs, each with its own 1 kΩ resistorAs listedVariesGPIO25 red; GPIO26 green. Green means below the chosen relative threshold, never safe air.
Joy-IT COM-KY012APB active piezo buzzerAs listedVariesMay 2024 manual: sound from voltage between S and minus; centre terminal unused. This is not a generic three-pin logic-input module. Use the separate regulated 4.5 V rail, not the heater rail or a GPIO; manufacturer current maximum is 30 mA.
onsemi P2N2222A TO-92, 330 Ω (1%) and 100 kΩ resistorsAs listedVariesExact transistor: pin 1 collector, 2 base, 3 emitter; use the datasheet package view. GPIO27 controls the base, never powers the buzzer.
Separate regulated 4.5 V ±5% output rail, at least 200 mA1VariesA separate bench supply output powers the selected relay/buzzer inside its documented 3–5 V range. Its GND joins common GND; positive remains off ESP32 power pins and off the 5 V heater rail.

Wiring

One bounded bare-sensor circuit. Heater and sensing-loop supply are 5.0 V ±0.1 V; ESP32 signals remain in the 3.3 V domain. Unknown comparator breakouts are not covered.

Logical MQ-2 bare-sensor heater, load resistor and 12 kΩ/10 kΩ ESP32 interface with qualified output stage

Open wiring diagram full size

  1. 1

    Disconnect USB and the external supply. Confirm the manufacturer pin-view orientation; the logical drawing is not a physical pin layout.

  2. 2

    Connect the bare MQ-2 H heater pair across external regulated 5.0 V ±0.1 V. Connect both A electrode pins to that same 5 V rail; join both B pins as RAW.

  3. 3

    Connect a separate RL = 10 kΩ from RAW to common GND. Connect RAW through 12 kΩ (1%) to the ADC node, then 10 kΩ (1%) from that node to GND.

  4. 4

    Connect only the divided node to GPIO34. Add 100 nF from that node to GND. There is no DOUT connection in this circuit.

  5. 5

    Join ESP32 GND, 5 V heater-supply GND and 4.5 V output-supply GND. Keep both external positive rails off USB/VIN/3V3 and separate from each other.

  6. 6

    GPIO25 -> 1 kΩ -> red LED anode; red cathode -> GND. GPIO26 -> a separate 1 kΩ -> green anode; green cathode -> GND.

  7. 7

    GPIO27 -> 330 Ω -> P2N2222A base (2); 100 kΩ base to emitter (3); emitter -> GND. Collector (1) -> buzzer minus; buzzer S -> separate regulated 4.5 V ±5%; centre unused.

  8. 8

    Before attaching GPIO34, check the divider values and output with a meter. Power USB first, then the heater/output supply; type d to disarm and switch both external rails off before USB to avoid back-power through a signal pin.

  9. 9

    Complete the sensor conditioning procedure, observe the actual warm-up trend, and record stable reference conditions before typing b then a. No automatic delay proves stability.

GPIO Mapping

SignalESP32 PinDirectionNotes
Divided RAWGPIO34Analog input12 kΩ upper / 10 kΩ lower, 1%; 100 nF to GND. Never RAW directly.
Sensor H pair / A pairExternal regulated 5.0 V ±0.1 VPowerNot ESP32 3V3; external positive remains off board power pins.
B pair RAWRL 10 kΩ to GNDAnalog nodeAlso feeds the upper 12 kΩ resistor; no DOUT.
Common referenceGNDGroundESP32 and both external supplies share GND; positive rails remain separate.
Red LEDGPIO25OutputOwn 1 kΩ series resistor; HIGH = relative threshold active.
Green LEDGPIO26OutputOwn 1 kΩ resistor; below threshold only while armed, not a safety indication.
Buzzer transistor baseGPIO27Output330 Ω base resistor; 100 kΩ base-emitter; HIGH switches the selected buzzer on.
Selected relay/buzzer powerExternal regulated 4.5 V ±5%PowerSeparate ≥200 mA rail, common GND. Not the 5.1 V worst-case heater rail.

Circuit Explanation

The A/B sensing element and RL form a resistance-to-voltage circuit. The extra 12 kΩ + 10 kΩ ADC divider also loads RAW: the effective load is 10 kΩ || 22 kΩ ≈ 6.875 kΩ. Do not reuse a manufacturer response curve as a ppm conversion for this altered load. The upper divider resistor is 12 kΩ; the lower is 10 kΩ, not reversed.

Engineering Explanation

Interface calculation: assume RAW can reach the full 5.1 V supply. Nominal ratio is 10/22, so 5.0 V becomes 2.273 V. With 1% resistors, maximum ratio is 10.1/(11.88+10.1): 5.1 V becomes 2.344 V. This leaves about 0.756 V below the classic ESP32 11 dB documented 3.1 V measurement ceiling, as well as margin below the GPIO logic supply. Even 5.25 V would stay below 2.413 V, but that does not permit exceeding the heater’s 5.1 V maximum. Readings below about 150 mV are outside the documented ADC measurement range. These calculations assume intact resistors, correct wiring, common ground and a powered ESP32; the divider is not fault-rated protection or isolation. Verify actual voltages before connecting the pin. The separate 4.5 V ±5% output rail spans 4.275–4.725 V, inside the selected relay/buzzer 3–5 V supply range. Do not simply parallel it with the 5 V heater rail. With a 330 Ω (1%) base resistor, 2.4 V GPIO HIGH at the classic ESP32 3.0 V minimum operating supply and a conservative 1.2 V base-emitter drop give about 3.60 mA before the small base pull-down current base current for the selected buzzer’s 30 mA maximum. This is a driver-design check, not an observed current or saturation measurement.

Libraries

  • Arduino-ESP32 3.3.2Classic ESP32-WROOM review baseline; analogReadResolution(12) and analogSetPinAttenuation(GPIO34, ADC_11db). No extra sensor library. No firmware compilation or hardware test is established by this example.

Code

Copy into Arduino IDE. Install any libraries noted in the component guides first.

esp32-fire-alarm-system.ino
// Classic ESP32-WROOM DevKit; Arduino-ESP32 3.3.2 review baseline.
// Bare Winsen MQ-2, RL 10k; RAW -> 12k -> GPIO34 -> 10k -> GND (1%).
// Educational relative-count demo, NOT a safety alarm or calibrated gas meter.
const int SENSOR_PIN = 34;
const int RED_PIN = 25, GREEN_PIN = 26, BUZZER_PIN = 27;
const int ON_OFFSET = 200;   // Illustrative raw counts, not a gas limit.
const int OFF_OFFSET = 100;  // Hysteresis below ON_OFFSET.
bool armed = false, baselineSet = false, active = false, sampled = false;
int baseline = 0, reading = 0;
unsigned long lastSample = 0;

bool usable() { return sampled && reading > 20 && reading < 3800; }

void setOutputs(bool enabled, bool alert) {
  digitalWrite(RED_PIN, enabled && alert ? HIGH : LOW);
  digitalWrite(GREEN_PIN, enabled && !alert ? HIGH : LOW);
  // Short bench chirp, not a fire-alarm cadence.
  digitalWrite(BUZZER_PIN, enabled && alert && millis() % 3000 < 200 ? HIGH : LOW);
}

void setup() {
  Serial.begin(115200);
  const int outputs[] = {RED_PIN, GREEN_PIN, BUZZER_PIN};
  for (int pin : outputs) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
  }
  pinMode(SENSOR_PIN, INPUT);
  analogReadResolution(12);
  analogSetPinAttenuation(SENSOR_PIN, ADC_11db);
  Serial.println("DISARMED. Complete sensor conditioning and observe baseline stability first.");
  Serial.println("b = capture reference count; a = arm demo; d = disarm. Not calibration.");
}

void loop() {
  if (millis() - lastSample >= 1000) {
    lastSample = millis();
    unsigned long sum = 0;
    for (int i = 0; i < 16; ++i) {
      sum += analogRead(SENSOR_PIN);
      delayMicroseconds(200);
    }
    reading = sum / 16;
    sampled = true;
    if (!usable()) { armed = false; active = false; }
    if (armed) {
      if (!active && reading >= baseline + ON_OFFSET) active = true;
      if (active && reading <= baseline + OFF_OFFSET) active = false;
    }
    Serial.printf("raw=%d reference=%d armed=%d thresholdState=%d\n",
                  reading, baseline, armed, active);
    if (!usable()) Serial.println("ADC near a rail: demo disabled; inspect power and wiring.");
  }
  while (Serial.available()) {
    char c = Serial.read();
    if (c == 'd' || c == 'b') { armed = false; active = false; }
    if (c == 'b') {
      baselineSet = usable() && reading <= 3500;
      if (baselineSet) baseline = reading;
      Serial.println(baselineSet ? "Reference captured; still disarmed." : "Reference refused.");
    }
    if (c == 'a') {
      armed = baselineSet && usable();
      Serial.println(armed ? "Demo armed; not a safety monitor." : "Capture a usable reference first.");
    }
  }
  setOutputs(armed && usable(), active);
}

Code Explanation

Startup and reset are disarmed with all outputs OFF. Once per second the sketch averages 16 raw ADC samples. Type b to capture a reference count only after independently checking conditioning and stability; type a to arm, d to disarm. The +200/+100 raw-count thresholds provide illustrative hysteresis, not a health or fire limit. Near-rail counts disable the output, but this cannot detect every disconnected sensor or wiring fault.

Expected Output

At 115200 baud, expect raw, reference, armed and thresholdState fields. A reboot never arms automatically. After b then a, outputs change only with the chosen relative-count thresholds. No ppm, AQI, gas identity, safe-air status or confirmed fire detection is produced.

Troubleshooting

  • Counts drift after switch-on Winsen specifies at least 48 hours initial preheating under its standard conditions (MQ135: over 48 hours). Storage may require additional aging. Later power-ups still need warm-up; log the actual trend under unchanged conditions. No universal short delay establishes stability or calibration.
  • ADC near zero or full scale Disarm, turn both supplies off, inspect H/A/B identification, common ground, RL and divider orientation. Measure the divided voltage before reconnecting GPIO34. Do not raise the threshold to conceal an electrical fault.
  • Output remains OFF Reboot is deliberately disarmed. Observe usable counts, type b then a; verify the exact active-HIGH output stage. Do not test with smoke or gas.
  • Reference changes with environment Humidity, temperature, oxygen, contamination and multiple gases influence MQ response. A stable baseline is a record of conditions, not proof of air safety or calibration.

Common Mistakes

  • Substituting an unidentified comparator module for the bare sensor circuit.
  • Connecting RAW, heater power or a 5 V DOUT to a GPIO.
  • Reversing the 12 kΩ upper and 10 kΩ lower divider resistors.
  • Treating a green LED or a plausible number as evidence of safe air.
  • Using a fixed 30-second timer as proof of conditioning or stability.

Testing Checklist

  • With power off, compare the H/A/B wiring with the manufacturer lead-view drawing.
  • Verify the 5.0 V ±0.1 V rail and the divided node with a meter before attaching the ESP32 input.
  • Complete initial conditioning; record actual power-up settling observations separately.
  • Check disarmed startup, b/a/d commands and output polarity using only low-voltage bench loads.
  • If demonstrating threshold logic without a sensor change, adjust the illustrative offsets in code; never create smoke or release gas.
  • Switch off the external supply before USB. These are checks to perform, not a claim that this build was tested.

Engineering Tips

  • The divider upper bound is an electrical calculation, not hardware verification.
  • A captured reference count is not a calibration.
  • Keep heater heat away from the ESP32 regulator and flammable materials.

Upgrade Ideas

  • Log raw counts with temperature, humidity and elapsed powered time.
  • Display the armed/disarmed state clearly on an OLED.

Real-World Applications

  • Supervised analog-interface lesson
  • Relative-count threshold and hysteresis demonstration

FAQs

Can this replace a certified alarm?

No. Continue using approved smoke, fire and gas safety equipment; this circuit is an educational demonstration only.

Can I reuse an AOUT/DOUT breakout?

Not without its exact schematic, heater specification and verified output limits. This page supports the bare sensor circuit only; there is no DOUT wire.

When is the sensor ready?

Initial manufacturer conditioning and subsequent warm-up are different. Observe the actual baseline; elapsed time or typing b does not demonstrate stability, selectivity or calibration.

Review, Testing, and References

Author: Abdul Mubeen and the ESP32 Engine editorial team. Last updated: 2026-11-10. Reviewed: wiring logic, Arduino code structure, beginner safety, and learning sequence.

Educational level: Intermediate. Estimated completion time: Assembly varies; initial sensor conditioning is separate (48+ hours). This project is for learning and prototyping; production or unattended hardware needs additional engineering review.

Check your result

Before treating this example as working on your hardware, compare the observed behavior with Expected Output and complete the checks on this page. If results differ, use Troubleshooting. Reading this tutorial does not establish successful compilation or hardware operation.

  • ADC1 analog input
  • Voltage divider protection
  • Threshold tuning