Wemos D1 Mini MQ-2 Gas Leak Detector with Buzzer and Wi-Fi Dashboard

Wemos D1 Mini MQ-2 gas leak detector on a breadboard with a buzzer and red and green LEDs

Make a Wemos D1 Mini (ESP8266) MQ-2 gas and smoke leak detector with buzzer, LEDs and a live Wi-Fi web dashboard. Wiring table, A0 resistor trick, tested code, calibration and Hindi explanation.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUWemos D1 Mini (ESP8266)
  • Parts7 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

Wemos D1 Mini MQ-2 gas leak detector on a breadboard with a buzzer and red and green LEDs

A gas leak in the kitchen is one of those problems you want to know about immediately, even when you are not in the room. In this beginner-friendly project we build a Wemos D1 Mini (ESP8266) MQ-2 gas and smoke leak detector with a loud buzzer, red/green status LEDs and a live Wi-Fi web dashboard that you can open on any phone connected to your home network. No app, no cloud account and no extra library is needed – everything uses the libraries that come with the ESP8266 Arduino core.

The MQ-2 reacts to LPG, propane, methane, butane, hydrogen, alcohol vapour and smoke, so it is ideal for a demonstration of a kitchen or workshop alarm. You will get the parts list, a pin-to-pin wiring table (including the important resistor trick for the D1 Mini analog pin), compile-tested code, a step-by-step build, calibration tips, troubleshooting and a FAQ, plus a simple Hindi explanation.

Safety note: this is a learning project, not a certified safety device. Hobby MQ sensors are not calibrated and can drift. Always keep a certified LPG/CO detector in your home and follow local safety rules.

How the MQ-2 Sensor Works

Inside the MQ-2 is a small tin-dioxide (SnO₂) sensing element heated by a tiny coil. In clean air its resistance is high. When combustible gas or smoke reaches the hot surface, the resistance falls. The breakout board turns this into a voltage on the AO (analog output) pin – more gas means a higher voltage. The board also has a DO pin with an on-board comparator and potentiometer, but we use AO so the software can show the actual level and you can change the alarm threshold in code.

Because the heater needs to reach a stable temperature, the readings are not reliable for the first minute after power-on (and the very first use of a new sensor needs a longer “burn-in” of several hours). The code therefore ignores alarms for the first 60 seconds and shows “Sensor warming up” on the web page.

Components Required

  • Wemos D1 Mini (ESP8266) – 1
  • MQ-2 gas sensor module (4-pin: VCC, GND, DO, AO) – 1
  • 180 kΩ resistor – 1 (for the analog input, explained below)
  • Active 5 V buzzer module or active buzzer – 1
  • Red LED and green LED – 1 each
  • 220 Ω resistors – 2 (for the LEDs)
  • Breadboard, jumper wires and a micro-USB cable (5 V, 1 A USB adapter recommended because the MQ-2 heater draws about 150 mA)

Wiring Table (Pin-to-Pin)

ModuleModule PinD1 Mini PinNotes
MQ-2VCC5VHeater needs 5 V
MQ-2GNDG (GND)
MQ-2AOA0 through a 180 kΩ resistorResistor in series between AO and A0 – see below
MQ-2DONot connectedOptional comparator output
Active buzzer+ (I/O)D5 (GPIO14)BUZZER_PIN = D5
Active buzzer–G (GND)
Red LEDAnode (long leg)D6 (GPIO12) via 220 ΩRED_LED = D6 – alarm
Green LEDAnode (long leg)D7 (GPIO13) via 220 ΩGREEN_LED = D7 – air OK
Both LEDsCathode (short leg)G (GND)

Why the 180 kΩ resistor?

The ESP8266 chip can only measure 0–1.0 V. The D1 Mini has a built-in voltage divider (220 kΩ + 100 kΩ) so its A0 pin accepts up to about 3.2 V. The MQ-2 module is powered from 5 V, so its AO can rise close to 5 V in strong gas. Adding 180 kΩ in series makes the total divider (180 k + 220 k) : 100 k, which scales 5.0 V to exactly 1.0 V at the chip. This protects the input and uses the full 0–1023 range.

Libraries Used (with Licenses)

  • ESP8266 Arduino core (includes ESP8266WiFi and ESP8266WebServer) – github.com/esp8266/Arduino – LGPL-2.1 license.
  • No third-party library is required. The sketch and the small HTML/JavaScript dashboard are original code written for this article.

Complete Wemos D1 Mini Code

Board used for the compile test: LOLIN(WEMOS) D1 R2 & mini (esp8266 core 3.x). Replace the Wi-Fi name and password before uploading.

// Wemos D1 Mini (ESP8266) MQ-2 Gas / Smoke Leak Detector with Web Dashboard
// Buzzer + red/green LEDs, live page at http://<ip>/ and JSON at /data
// Uses only libraries bundled with the ESP8266 Arduino core
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";

const int GAS_PIN    = A0;   // MQ-2 AO (through 180k series resistor)
const int BUZZER_PIN = D5;   // GPIO14, active buzzer (+)
const int RED_LED    = D6;   // GPIO12, via 220 ohm
const int GREEN_LED  = D7;   // GPIO13, via 220 ohm

int threshold = 400;                      // ADC value (0-1023) that triggers the alarm
const unsigned long WARMUP_MS = 60000UL;  // MQ-2 heater warm-up time
int gasValue = 0;
bool alarmOn = false;

ESP8266WebServer server(80);

const char PAGE[] PROGMEM = R"rawliteral(
<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Gas Monitor</title>
<style>body{font-family:Arial;text-align:center;background:#f4f6f8}
.card{background:#fff;max-width:340px;margin:30px auto;padding:20px;border-radius:12px;box-shadow:0 2px 8px #0002}
#v{font-size:48px;font-weight:bold}#s{font-size:22px;padding:8px;border-radius:8px;color:#fff}</style></head>
<body><div class="card"><h2>MQ-2 Gas Monitor</h2><div id="v">--</div><p>ADC value (0-1023)</p>
<div id="s">Loading...</div><p>Threshold: <span id="t"></span></p></div>
<script>
async function upd(){try{const r=await fetch('/data');const d=await r.json();
document.getElementById('v').textContent=d.gas;document.getElementById('t').textContent=d.threshold;
const s=document.getElementById('s');
if(d.warmup){s.textContent='Sensor warming up';s.style.background='#888';}
else if(d.alarm){s.textContent='GAS DETECTED!';s.style.background='#d32f2f';}
else{s.textContent='Air OK';s.style.background='#2e7d32';}}catch(e){}}
setInterval(upd,1000);upd();
</script></body></html>)rawliteral";

void handleRoot() {
  server.send_P(200, "text/html", PAGE);
}

void handleData() {
  bool warming = millis() < WARMUP_MS;
  String json = "{\"gas\":" + String(gasValue) +
                ",\"threshold\":" + String(threshold) +
                ",\"alarm\":" + String(alarmOn ? "true" : "false") +
                ",\"warmup\":" + String(warming ? "true" : "false") + "}";
  server.send(200, "application/json", json);
}

int readGasAverage() {
  long sum = 0;
  for (int i = 0; i < 10; i++) {
    sum += analogRead(GAS_PIN);
    delay(5);
  }
  return sum / 10;
}

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

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.print("Connecting to WiFi");
  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - start < 20000) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Open http://");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("WiFi failed - alarm still works offline");
  }

  server.on("/", handleRoot);
  server.on("/data", handleData);
  server.begin();
}

void loop() {
  server.handleClient();

  static unsigned long lastRead = 0;
  if (millis() - lastRead >= 500) {
    lastRead = millis();
    gasValue = readGasAverage();
    bool warming = millis() < WARMUP_MS;
    alarmOn = !warming && gasValue >= threshold;

    digitalWrite(RED_LED, alarmOn ? HIGH : LOW);
    digitalWrite(GREEN_LED, (!alarmOn && !warming) ? HIGH : LOW);
    Serial.printf("Gas: %d  %s\n", gasValue, warming ? "(warming up)" : (alarmOn ? "ALARM" : "OK"));
  }

  // beep pattern while alarm is active: 200 ms on / 200 ms off
  if (alarmOn) {
    digitalWrite(BUZZER_PIN, (millis() / 200) % 2 ? HIGH : LOW);
  } else {
    digitalWrite(BUZZER_PIN, LOW);
  }
}

Code Explanation

  • readGasAverage() takes 10 analog readings 5 ms apart and averages them to reduce noise.
  • threshold = 400: when the averaged value reaches 400 (of 1023) the alarm turns on. Calibrate this for your sensor (see below).
  • WARMUP_MS: for the first 60 s the alarm is disabled and both LEDs stay off while the heater stabilises.
  • Non-blocking design: the sensor is read every 500 ms using millis(), so the web server keeps responding instantly. The buzzer beeps 200 ms on / 200 ms off using millis() / 200.
  • Web dashboard: / serves a small HTML page stored in flash (PROGMEM). Its JavaScript calls /data every second and updates the number and the coloured status box without reloading the page.
  • /data returns JSON like {"gas":182,"threshold":400,"alarm":false,"warmup":false}, which you can also read from Home Assistant, Node-RED or a Python script.
  • If Wi-Fi does not connect within 20 s the detector still works offline with the buzzer and LEDs.

Step-by-Step Build Instructions

  1. Install the ESP8266 boards package: add https://arduino.esp8266.com/stable/package_esp8266com_index.json in File → Preferences → Additional Boards Manager URLs, then install “esp8266” from Boards Manager.
  2. Plug the D1 Mini into the breadboard. Connect its 5V and G pins to the rails.
  3. Connect the MQ-2: VCC → 5V, GND → G. Put the 180 kΩ resistor between the AO pin and A0.
  4. Connect the buzzer (+) to D5 and (–) to GND. Connect the red LED to D6 and the green LED to D7, each through a 220 Ω resistor, with the short legs to GND.
  5. Open the code, enter your Wi-Fi name and password, select LOLIN(WEMOS) D1 R2 & mini and the COM port, and upload.
  6. Open the Serial Monitor at 115200 baud. Note the IP address printed, e.g. Open http://192.168.1.45.
  7. Open that address in your phone browser (same Wi-Fi). For one minute you will see “Sensor warming up”, then “Air OK” with the green LED on.
  8. Test safely: hold an unlit lighter near the sensor and press the gas button briefly for one second. The value rises, the red LED lights, the buzzer beeps and the page turns red. Never use an open flame.

Calibrating the threshold

Let the sensor run for at least 15 minutes in clean air and note the typical value (often 80–250). Set threshold to roughly 2× that value for a sensitive alarm, or higher to avoid false alarms from cooking fumes. Upload again after changing it.

सरल हिंदी में समझें (Simple Hindi Explanation)

इस प्रोजेक्ट में MQ-2 सेंसर हवा में LPG, धुआँ (smoke) या दूसरी ज्वलनशील गैस को पहचानता है। जितनी ज़्यादा गैस, उतना ज़्यादा वोल्टेज AO पिन पर आता है। Wemos D1 Mini इस वोल्टेज को A0 पिन से पढ़ता है। क्योंकि D1 Mini का A0 सिर्फ लगभग 3.2V तक ही सह सकता है, इसलिए हम बीच में 180kΩ रेज़िस्टर लगाते हैं ताकि 5V सुरक्षित रूप से नापा जा सके।

जब वैल्यू तय सीमा (threshold = 400) से ऊपर जाती है, तो लाल LED जलती है और buzzer बजता है। सामान्य हवा में हरी LED जलती है। साथ ही D1 Mini अपने Wi-Fi से एक छोटा वेब पेज चलाता है – मोबाइल पर IP एड्रेस खोलकर आप लाइव गैस वैल्यू देख सकते हैं। ध्यान रखें: चालू होने के बाद सेंसर को गर्म होने में लगभग 1 मिनट लगता है, और यह केवल सीखने का प्रोजेक्ट है – असली सुरक्षा के लिए सर्टिफाइड गैस डिटेक्टर ज़रूर लगाएँ।

Troubleshooting

ProblemFix
Value is always 1023A0 is overloaded – check that the 180 kΩ resistor is in series, not to ground. Make sure AO (not DO) is used.
Value is always 0 or very lowAO wire loose or MQ-2 not powered. The sensor should feel warm after a minute.
Alarm triggers immediately after warm-upA brand-new sensor needs a burn-in of several hours. Run it overnight, then raise the threshold if needed.
Web page does not openPhone must be on the same Wi-Fi network. Check the IP in Serial Monitor. 5 GHz-only networks are not supported by the ESP8266 – use 2.4 GHz.
D1 Mini resets when the buzzer soundsThe USB supply is too weak. Use a 5 V 1 A adapter and a short, good USB cable.
Buzzer makes only a clickYou have a passive buzzer. Use an active buzzer, or replace digitalWrite with tone(BUZZER_PIN, 2000).

Ideas to Extend the Project

  • Add a relay module to switch on an exhaust fan when gas is detected.
  • Send a Telegram or email notification when the alarm triggers.
  • Add a DHT22 so the dashboard also shows temperature and humidity.
  • Log values to Google Sheets or ThingSpeak for long-term trends.

Frequently Asked Questions

Can the MQ-2 show the gas concentration in ppm?

Only approximately. Converting to ppm requires measuring the sensor resistance in clean air (R0) and using the curves in the datasheet. For an alarm, a raw threshold is simpler and more reliable.

Can I use a NodeMCU instead of the D1 Mini?

Yes. NodeMCU boards also have a divider on A0 (usually the same 220k/100k). Use the same pin names (D5, D6, D7) and select “NodeMCU 1.0” as the board.

Which gases does the MQ-2 detect?

LPG, propane, butane, methane, hydrogen, alcohol and smoke. For carbon monoxide use an MQ-7; for general air quality use an MQ-135.

Can I use the DO pin instead?

Yes – DO goes LOW when gas passes the threshold set by the blue potentiometer on the module. You would then read it with digitalRead, but you lose the live level on the dashboard.

Is it safe to leave it running all the time?

The circuit itself is low-power and safe, but the MQ-2 heater runs continuously and gets warm. Mount it in a ventilated enclosure away from water, and remember it is not a certified alarm.

Related Projects

Browse more ESP8266 Projects on Arduino Project Hub.

ESP8266 NodeMCU Home Automation: 4-Relay Web Control (No App)

NodeMCU ESP8266 connected to a 4-channel relay module with a phone showing on/off switch buttons and a light bulb – ESP8266 home automation

Control lights and fans from your phone with NodeMCU ESP8266 and a 4-channel relay. Safe pin choice, wiring tables, full code and troubleshooting.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUNodeMCU (ESP8266)
  • Parts5 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

Control your lights, fan and sockets from your phone with this ESP8266 NodeMCU home automation project. The NodeMCU joins your home Wi-Fi and serves a simple, mobile-friendly web page with four big buttons. Each tap toggles one channel of a 4-channel relay module, which can switch AC appliances. There is no cloud, no app installation and no subscription: everything runs locally on the ESP8266, so it keeps working even when the internet is down (as long as your router is on).

⚠️ Safety first: relays switch mains voltage (230 V AC in India), which can kill. If you are a beginner, test with a 5 V LED or a 12 V DC lamp first. For mains wiring, use a proper enclosure, insulated terminals, a fuse, and get help from a qualified electrician.

How It Works

A relay is an electrically controlled switch. The ESP8266 drives the relay module’s IN pins; the module’s optocoupler and transistor energise the relay coil, which closes the COM–NO contact and powers the appliance. Most low-cost relay boards are active-LOW: the relay turns ON when the input pin is LOW. The code handles this with a single ACTIVE_LOW setting. The web page uses simple links like /toggle?ch=0; the ESP8266 flips that relay and redirects the browser back to the main page so the buttons show the new state.

Components Required

  • NodeMCU ESP8266 (ESP-12E) development board – 1
  • 4-channel 5 V relay module (with optocouplers) – 1
  • 5 V 2 A USB power supply (powers NodeMCU and relays through VIN)
  • Jumper wires (female-to-female)
  • For loads: appliance, insulated wire, screw terminals, enclosure, fuse

Wiring Table (Pin-to-Pin)

These four pins are chosen because they do not affect the ESP8266 boot mode. Avoid D3, D4 and D8 for relays – they are boot-strapping pins and can stop the board from starting.

Relay Module PinNodeMCU PinGPIOIn Code
VCCVIN (5 V from USB)—Relay coils need 5 V
GNDGND—Common ground
IN1D1GPIO5relayPins[0] – “Light”
IN2D2GPIO4relayPins[1] – “Fan”
IN3D5GPIO14relayPins[2] – “Socket”
IN4D6GPIO12relayPins[3] – “Lamp”
Relay ContactConnect To
COMLive (phase) wire from the supply, through a fuse
NO (normally open)Live wire going to the appliance
NCLeave unused (it would be ON when the relay is OFF)
NeutralGoes directly to the appliance, not through the relay

Most 5 V optocoupler relay modules switch reliably with the 3.3 V signal from the NodeMCU. If a relay clicks unreliably, remove the JD-VCC jumper and feed JD-VCC with 5 V while VCC gets 3.3 V, so the opto input is driven at 3.3 V logic.

Software and Libraries

  • ESP8266 Arduino core: add https://arduino.esp8266.com/stable/package_esp8266com_index.json in Preferences and install “esp8266” from Boards Manager – esp8266/Arduino core (LGPL-2.1).
  • ESP8266WiFi.h and ESP8266WebServer.h are part of that core; no extra library is required.
  • The sketch is original code written for this tutorial.

Complete Code

// ESP8266 (NodeMCU) 4-Channel Relay Home Automation - Web Control
// Board: "NodeMCU 1.0 (ESP-12E Module)" from the ESP8266 Arduino core
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid     = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

// D1=GPIO5, D2=GPIO4, D5=GPIO14, D6=GPIO12 (safe at boot)
const int relayPins[4] = {D1, D2, D5, D6};
const char* names[4]   = {"Light", "Fan", "Socket", "Lamp"};
bool relayOn[4] = {false, false, false, false};
const bool ACTIVE_LOW = true;   // most relay modules switch ON with LOW

ESP8266WebServer server(80);

void applyRelay(int i) {
  bool level = relayOn[i] ? !ACTIVE_LOW : ACTIVE_LOW;
  digitalWrite(relayPins[i], level ? HIGH : LOW);
}

String page() {
  String h = "<!DOCTYPE html><html><head><meta charset='utf-8'>"
             "<meta name='viewport' content='width=device-width,initial-scale=1'>"
             "<title>Home Automation</title><style>body{font-family:Arial;text-align:center;background:#111827;color:#fff}"
             "a{display:block;margin:12px auto;max-width:320px;padding:16px;border-radius:10px;color:#fff;text-decoration:none;font-size:20px}"
             ".on{background:#16a34a}.off{background:#475569}</style></head><body><h1>ESP8266 Home Automation</h1>";
  for (int i = 0; i < 4; i++) {
    h += "<a class='" + String(relayOn[i] ? "on" : "off") + "' href='/toggle?ch=" + String(i) + "'>";
    h += String(names[i]) + ": " + (relayOn[i] ? "ON" : "OFF") + "</a>";
  }
  h += "</body></html>";
  return h;
}

void handleRoot() { server.send(200, "text/html", page()); }

void handleToggle() {
  if (server.hasArg("ch")) {
    int ch = server.arg("ch").toInt();
    if (ch >= 0 && ch < 4) {
      relayOn[ch] = !relayOn[ch];
      applyRelay(ch);
    }
  }
  server.sendHeader("Location", "/");   // redirect back to the main page
  server.send(303);
}

void setup() {
  Serial.begin(115200);
  for (int i = 0; i < 4; i++) {
    pinMode(relayPins[i], OUTPUT);
    applyRelay(i);                    // start with everything OFF
  }
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
  Serial.print("\nOpen http://");
  Serial.println(WiFi.localIP());
  server.on("/", handleRoot);
  server.on("/toggle", handleToggle);
  server.begin();
}

void loop() {
  server.handleClient();
}

Code Explanation

  • relayPins[] and names[] keep the pins and button labels together; rename the labels to match your rooms.
  • applyRelay() converts the logical ON/OFF state into the correct pin level for active-LOW or active-HIGH boards.
  • In setup() every relay is set OFF before Wi-Fi starts, so appliances do not switch on unexpectedly after a power cut.
  • handleToggle() validates the channel number, flips the state, and sends a 303 redirect back to the main page.
  • page() builds the HTML each time, so the button colour (green = ON, grey = OFF) always matches the real state.

Step-by-Step Instructions

  1. Install the ESP8266 board package and select NodeMCU 1.0 (ESP-12E Module).
  2. Wire the relay module as in the table (VCC → VIN, GND → GND, IN1–IN4 → D1, D2, D5, D6). Do not connect any mains load yet.
  3. Enter your Wi-Fi SSID and password in the code and upload.
  4. Open Serial Monitor at 115200 baud and note the IP address.
  5. Open that IP on your phone. Tap each button – you should hear the relay click and see its LED light up.
  6. If buttons work in reverse (ON shows when relay is off), set ACTIVE_LOW = false.
  7. Test with a low-voltage load, then (with an electrician if needed) wire your appliance through COM and NO inside an enclosure.
  8. In your router settings, reserve a fixed IP for the NodeMCU so the address never changes. Add the page to your phone home screen for one-tap access.

Troubleshooting

ProblemFix
All relays click ON at bootNormal for a moment on some boards; avoid D3/D4/D8. The code sets them OFF immediately.
Board keeps resetting when relays switchPower supply too weak – use a 5 V 2 A adapter; add a 470 µF capacitor across VIN and GND.
Relay LED lights but no clickCoil not getting 5 V; check VCC/JD-VCC jumper.
Page not loadingPhone on mobile data or guest Wi-Fi; check IP in Serial Monitor.
ON/OFF reversedChange ACTIVE_LOW.

Next Steps

  • Add Blynk IoT or MQTT for control from anywhere.
  • Add manual wall switches as inputs so both switch and phone work.
  • Save relay states to EEPROM so they survive a reboot.
  • Add password protection with server.authenticate().

Frequently Asked Questions

Can I control it from outside my home?

This version is local-only, which is more secure. For remote control, use a cloud service like Blynk IoT, Sinric Pro or an MQTT broker with TLS.

Can I use ESP32 instead?

Yes – change the includes to WiFi.h and WebServer.h, use WebServer server(80); and choose GPIOs such as 23, 22, 21, 19.

How much load can the relay handle?

Typical SRD-05VDC-SL-C relays are rated 10 A at 250 V AC, but stay well below that (e.g., under 5 A) on cheap modules, and never switch heaters or ACs without proper contactors.

Does it work with Alexa or Google Home?

Not directly; you can integrate it via Sinric Pro, Home Assistant or the Espalexa library.

Related Projects

Browse more ESP8266 Projects on Arduino Project Hub.