Yarana Iot Guru
Published © MIT

DIY Gas Sensor Project with ESP32: Smoke Detection

Detect harmful gases or smoke in real time using ESP32 and an MQ-2 sensor — view alerts instantly! by YaranaIoT Guru

BeginnerFull instructions provided8 hours8
DIY Gas Sensor Project with ESP32: Smoke Detection

Things used in this project

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

💻 Code Example

C/C++
/*
  DIY Gas Sensor Project with ESP32: Smoke Detection
  Author: YaranaIoT Guru
*/

#include <WiFi.h>
#include <WebServer.h>

const char* ssid = "YourWiFiName";
const char* password = "YourWiFiPassword";

WebServer server(80);

const int gasPin = 34;   // Analog input from MQ-2
const int buzzer = 25;
const int led = 26;

int gasValue = 0;
int threshold = 500;  // Adjust as needed

String buildPage() {
  String html = "<html><head><meta charset='UTF-8'><title>ESP32 Gas Monitor</title>";
  html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
  html += "<style>body{text-align:center;font-family:Arial;background:#f4f4f4;}h2{color:#333;}p{font-size:20px;}</style></head><body>";
  html += "<h2>🔥 ESP32 Gas & Smoke Detection</h2><p>Gas Level: " + String(gasValue) + "</p>";
  if (gasValue > threshold) html += "<p style='color:red;'>⚠️ DANGER: Gas Level High!</p>";
  else html += "<p style='color:green;'>✅ Safe Environment</p>";
  html += "<p><small>By YaranaIoT Guru</small></p></body></html>";
  return html;
}

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

void setup() {
  Serial.begin(115200);
  pinMode(buzzer, OUTPUT);
  pinMode(led, OUTPUT);

  WiFi.begin(ssid, password);
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("\nConnected! IP: " + WiFi.localIP().toString());
  server.on("/", handleRoot);
  server.begin();
}

void loop() {
  gasValue = analogRead(gasPin);
  Serial.println(gasValue);

  if (gasValue > threshold) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(buzzer, LOW);
    digitalWrite(led, LOW);
  }

  server.handleClient();
  delay(1000);
}

Credits

Yarana Iot Guru
28 projects • 0 followers
Yarana Iot Guru Yarana IoT Guru: Arduino, ESP32, GSM, NodeMCU & more. Projects, Tutorials & App Development. Innovate with us!
Thanks to YaranaIoT Guru.

Comments