#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
// --- WIFI CONNECTIONS (Wokwi uses this free virtual Wi-Fi) ---
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// --- TELEGRAM SETUP ---
#define BOT_TOKEN "7886923581:AAEJiCG5BnWdZQ5pHEC8QPsjLeHJly_Swtk" // Paste your BotFather token here
#define CHAT_ID "1213332037" // Paste your Chat ID here
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
// --- HARDWARE PINS ---
const int gasSensorPin = 34; // Potentiometer acting as MQ-6
const int fanRelayPin = 25; // Relay / LED acting as Exhaust Fan
const int buzzerPin = 26; // Buzzer
// --- VARIABLES ---
int gasLevel = 0;
int safetyThreshold = 2000; // ESP32 analog reads from 0 to 4095
bool isAlarmActive = false; // To prevent spamming Telegram messages
void setup() {
Serial.begin(115200);
pinMode(gasSensorPin, INPUT);
pinMode(fanRelayPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Keep fan and buzzer OFF at start
digitalWrite(fanRelayPin, LOW);
digitalWrite(buzzerPin, LOW);
// Connect to Wi-Fi
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Connected!");
// Required for Telegram API security
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
// Send a startup message to your phone
bot.sendMessage(CHAT_ID, "🟢 System Online: Gas Monitoring Active.", "");
}
void loop() {
// Read the "gas" level from the potentiometer
gasLevel = analogRead(gasSensorPin);
Serial.print("Gas Level: ");
Serial.println(gasLevel);
// IF GAS EXCEEDS THRESHOLD
if (gasLevel > safetyThreshold) {
digitalWrite(fanRelayPin, HIGH); // Turn ON Exhaust Fan
tone(buzzerPin, 1000); // Turn ON Buzzer with a 1000Hz tone
// Only send the Telegram message once per leak to avoid spam
if (!isAlarmActive) {
Serial.println("ALARM: Sending Telegram Message!");
bot.sendMessage(CHAT_ID, "🚨 DANGER: High Gas Leak Detected! Exhaust Fan Activated automatically.", "");
isAlarmActive = true;
}
}
// IF GAS RETURNS TO NORMAL
else {
digitalWrite(fanRelayPin, LOW); // Turn OFF Fan
noTone(buzzerPin); // Turn OFF Buzzer
// Send a "safe" message once the room clears
if (isAlarmActive) {
Serial.println("SAFE: Sending Telegram Message!");
bot.sendMessage(CHAT_ID, "✅ SAFE: Gas cleared. Exhaust Fan turned off.", "");
isAlarmActive = false;
}
}
delay(1000); // Check every 1 second
}