#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define GAS_PIN 34
#define LED_PIN 14
#define BUZZER_PIN 27
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Telegram bot info
String BOT_TOKEN = "8388279702:AAGEUp9tiZznlAoI9_tKzdgswPrbB3EAlDA";
String CHAT_ID = "7835992814";
// WiFi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Ngưỡng phát hiện gas
int thresholdValue = 2500;
// Tránh spam telegram
bool alertSent = false;
unsigned long lastAlertTime = 0;
void sendTelegram(String message) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "https://api.telegram.org/bot" + BOT_TOKEN +
"/sendMessage?chat_id=" + CHAT_ID +
"&text=" + message;
http.begin(url);
http.GET();
http.end();
}
}
void setup() {
Serial.begin(115200);
pinMode(GAS_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
// WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
Serial.println(" Connected!");
// OLED
oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
oled.clearDisplay();
oled.setTextSize(2);
oled.setTextColor(WHITE);
oled.setCursor(0, 0);
oled.println("Gas Monitor");
oled.display();
delay(1000);
}
void loop() {
int gasValue = analogRead(GAS_PIN);
Serial.println(gasValue);
oled.clearDisplay();
oled.setCursor(0, 0);
oled.setTextSize(1);
oled.print("Gas Value: ");
oled.println(gasValue);
// =============================
// GAS VƯỢT NGƯỠNG
// =============================
if (gasValue > thresholdValue) {
oled.setTextSize(2);
oled.setCursor(0, 20);
oled.println("DANGER!");
oled.display();
// LED + Buzzer nhấp nháy
digitalWrite(LED_PIN, HIGH);
tone(BUZZER_PIN, 1500);
delay(200);
digitalWrite(LED_PIN, LOW);
noTone(BUZZER_PIN);
// Gửi Telegram tránh spam mỗi 10 giây 1 lần
if (!alertSent || millis() - lastAlertTime > 10000) {
sendTelegram("⚠️ CẢNH BÁO! Khí gas vượt ngưỡng nguy hiểm!\nGiá trị: " + String(gasValue));
alertSent = true;
lastAlertTime = millis();
}
}
// =============================
// GAS AN TOÀN
// =============================
else {
oled.setTextSize(2);
oled.setCursor(0, 20);
oled.println("SAFE");
oled.display();
digitalWrite(LED_PIN, LOW);
noTone(BUZZER_PIN);
alertSent = false; // reset để nếu lần sau vượt ngưỡng sẽ gửi cảnh báo
}
delay(200);
}