#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
// Gas Sensor
#define GAS_PIN 35 // Change to the desired analog input pin for MQ2 gas sensor
// LED
#define POTENTIOMETER_PIN 35 // Potentiometer input pin
#define LED_PIN 26 // LED output pin
// Wi-Fi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Telegram Bot
const char* BOTtoken = "";
const char* CHAT_ID = "";
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
unsigned long previousGasMillis = 0;
const unsigned long gasInterval = 1000; // Check gas leakage every 1 second
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Send welcome message to Telegram
bot.sendMessage(CHAT_ID, "Welcome to the Gas Leakage Detection Bot!", "");
// Request status update
bot.sendMessage(CHAT_ID, "/status Please provide the current status by sending the command.", "");
pinMode(GAS_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
checkMessages();
unsigned long currentGasMillis = millis();
if (currentGasMillis - previousGasMillis >= gasInterval) {
previousGasMillis = currentGasMillis;
int gasValue = analogRead(GAS_PIN);
Serial.print("Gas Value: ");
Serial.println(gasValue);
if (gasValue > 200) {
// Gas detected
bot.sendMessage(CHAT_ID, "Gas leakage detected!", "");
Serial.println("Gas Leakage Detected!");
}
}
int analogValue = analogRead(POTENTIOMETER_PIN);
int brightness = map(analogValue, 0, 4095, 0, 255);
analogWrite(LED_PIN, brightness);
delay(100);
}
void checkMessages() {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
for (int i = 0; i < numNewMessages; i++) {
String chatId = String(bot.messages[i].chat_id);
String text = bot.messages[i].text;
if (text.equalsIgnoreCase("/status")) {
bot.sendMessage(chatId, "Gas Status: Normal", "");
}
}
if (numNewMessages > 0) {
bot.last_message_received = bot.messages[numNewMessages - 1].update_id;
}
}