#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <DHT.h>
// ===== WiFi =====
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ===== Telegram =====
#define BOT_TOKEN "8738358175:AAHLDw7FbrnbT5z9lR2DkO9I_gyxt174piM"
#define CHAT_ID "6600509098"
WiFiClientSecure client;
UniversalTelegramBot bot(BOT_TOKEN, client);
// ===== Sensors =====
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
#define MQ_PIN 34
// ===== Limits =====
float tempLimit = 35.0;
int gasLimit = 2000;
// ===== Control =====
bool alertSent = false;
// ===== Timer =====
unsigned long lastTime = 0;
unsigned long interval = 10000; // 10 sec
// ================= SETUP =================
void setup() {
Serial.begin(115200);
dht.begin();
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected!");
client.setInsecure(); // Required for Telegram
bot.sendMessage(CHAT_ID, "✅ ESP32 Monitoring Started", "");
}
// ================= LOOP =================
void loop() {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
int gas = analogRead(MQ_PIN);
// Check sensor error
if (isnan(temp) || isnan(hum)) {
Serial.println("DHT Error!");
delay(2000);
return;
}
// ===== Live Update every 10 sec =====
if (millis() - lastTime > interval) {
lastTime = millis();
String message = "📊 Live Update:\n";
message += "🌡 Temperature: " + String(temp) + " °C\n";
message += "💧 Humidity: " + String(hum) + " %\n";
message += "🌫 Gas Level: " + String(gas);
bot.sendMessage(CHAT_ID, message, "");
}
// ===== Alert System =====
if ((temp > tempLimit || gas > gasLimit) && !alertSent) {
String alertMsg = "🚨 ALERT: Air Quality Warning!\n";
alertMsg += "🌡 Temperature: " + String(temp) + " °C\n";
alertMsg += "💧 Humidity: " + String(hum) + " %\n";
alertMsg += "🌫 Gas Level: " + String(gas) + " (High)\n";
alertMsg += "⚠ Action Required!";
bot.sendMessage(CHAT_ID, alertMsg, "");
alertSent = true;
}
// ===== Reset Alert =====
if (temp <= tempLimit && gas <= gasLimit) {
alertSent = false;
}
delay(100); // small delay for stability
}