#include <Wire.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#define WIFI_SSID "Yousra"
#define WIFI_PASSWORD "1234567890"
const char* BOT_TOKEN = "7130187961:AAFFaP2LQDHCdy6gJtOPTeqF0M5GqdTm_i4";
const long CHAT_ID = 1724932489;
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
int flameSensorPin = 27; // Flame sensor on pin 27
int redLedPin = 4; // Red LED on pin 4
int buzzerPin = 14; // Buzzer on pin 14
int relayPin = 23; // Relay on pin 23
void sendTelegramMessage(String message) {
if (WiFi.status() == WL_CONNECTED) {
bot.sendMessage(String(CHAT_ID), message, "");
Serial.println("Message sent successfully");
} else {
Serial.println("WiFi not connected");
}
}
void setup() {
pinMode(redLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(flameSensorPin, INPUT);
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, HIGH); // Initial state of relay set to OFF
Serial.begin(9600);
// Initialization of LEDC for buzzer control
ledcSetup(0, 5000, 8); // Initialize LEDC channel 0 with a frequency of 5000Hz and a resolution of 8 bits
ledcAttachPin(buzzerPin, 0); // Attach the buzzer pin to LEDC channel 0
// Connect to WiFi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
}
void loop() {
int sensorValue = digitalRead(flameSensorPin); // Digital reading of the flame sensor
if (sensorValue == LOW) { // If a flame is detected (LOW means flame detected for this type of sensor)
// Activate the alarm and send message
digitalWrite(redLedPin, HIGH);
ledcWriteTone(0, 4000); // Set the buzzer to emit a sound at 4000Hz
digitalWrite(relayPin, LOW); // Activate the relay (inverted logic for the green light)
Serial.println("Danger Detected! Alarm triggered.");
sendTelegramMessage("Alert: Fire detected 🚨🚨 !");
// Keep the alarm on for 5 seconds
delay(1000);
// Deactivate the alarm after 5 seconds
digitalWrite(redLedPin, LOW);
ledcWriteTone(0, 0); // Stop the buzzer
digitalWrite(relayPin, HIGH); // Deactivate the relay (inverted logic for the green light)
Serial.println("Alarm deactivated after 5 seconds.");
} else {
// Ensure that the alarm stays off when no danger is detected
digitalWrite(redLedPin, LOW);
ledcWriteTone(0, 0); // Stop the buzzer
digitalWrite(relayPin, HIGH); // Deactivate the relay (inverted logic for the green light)
Serial.println("No Danger Detected.");
}
delay(1000); // Delay for 2 seconds before reading the sensor again
}