ESP32 Gas Leak Detection System with MQ Sensor and LED Alarm – DIY Project

 

Here's a step-by-step breakdown of this Gas Leak Detection System project:


Components Used

The setup consists of three main parts: an MQ-series gas sensor (the blue module on the left), an ESP32 microcontroller (center), and a red LED indicator (top right).

Code:

void setup() {
  Serial.begin(115200);
  pinMode(2, OUTPUT);
}
void loop() {
  int gasvalue = analogRead(4);
  Serial.print("Gas Sensor Value: ");
  Serial.print(gasvalue);
  if(gasvalue<=700){
    digitalWrite(2, HIGH);
    Serial.println("Danger ! Gas leak Detected!");
  }
  else{
    digitalWrite(2, LOW);
    Serial.println("Environment safe");
  }
  delay(2000);
}



Hardware Wiring

The gas sensor has four pins (A0, DOUT, GND, VCC) connected to the ESP32. VCC and GND provide power to the sensor (the red and green wires going to the ESP32's power and ground pins). The A0 (analog output) pin carries the sensor's analog reading to one of the ESP32's analog-capable GPIO pins. The red LED is wired to a GPIO pin on the ESP32 to act as a visual alarm.

Diagram.json:

{
  "version": 1,
  "author": "Syed Vajith",
  "editor": "wokwi",
  "parts": [
    { "type": "board-esp32-devkit-c-v4", "id": "esp", "top": 48, "left": 62.44, "attrs": {} },
    { "type": "wokwi-gas-sensor", "id": "gas1", "top": 89.1, "left": -108.2, "attrs": {} },
    { "type": "wokwi-led", "id": "led1", "top": 25.2, "left": 234.2, "attrs": { "color": "red" } }
  ],
  "connections": [
    [ "esp:TX", "$serialMonitor:RX", "", [] ],
    [ "esp:RX", "$serialMonitor:TX", "", [] ],
    [ "gas1:GND", "esp:GND.1", "black", [ "h28.8", "v76" ] ],
    [ "gas1:VCC", "esp:5V", "red", [ "h19.2", "v114.3" ] ],
    [ "gas1:DOUT", "esp:4", "green", [ "h19.2", "v-0.3", "h9.6", "v-86.4", "h124.8", "v163.2" ] ],
    [ "led1:C", "esp:GND.3", "green", [ "v0" ] ],
    [ "led1:A", "esp:2", "green", [ "v144" ] ]
  ],
  "dependencies": {}
}

How It Works (Logic Flow)

  1. Power On — The ESP32 boots up and initializes the gas sensor and LED pin.
  2. Sensor Reading — The gas sensor continuously measures air quality. It outputs an analog voltage value — lower values indicate higher gas concentration.
  3. Threshold Check — The ESP32 reads the analog value and compares it against a preset danger threshold.
  4. Danger Detected — As seen in the serial output at the bottom, the value is 0, which triggers the condition: "Danger ! Gas leak Detected!".
  5. LED Activation — When danger is detected, the ESP32 turns ON the red LED to visually alert that a gas leak is present.
  6. Serial Logging — The status is continuously printed to the serial monitor for monitoring, repeating the message every loop cycle.

Serial Output Explanation

The repeated message Gas Sensor Value: 0 Danger ! Gas leak Detected! tells us the sensor is returning a value of 0, which the code interprets as a dangerous gas level, triggering both the LED and the alert message.

Comments