#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h> // Include ArduinoJson library
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Google Script deployment URL
const char* googleScriptURL = "https://script.google.com/a/macros/student.uitm.edu.my/s/AKfycbyBgGPd9C3GbF1eh7JyZ0DkaJeEUQx-SiJhopH3ojxOp_q8_fNmBH_Qz7StOS5eyu0K/exec";
// Pins for components
const int photoelectricPin = 4; // Simulated by a button
const int buzzerPin = 15;
const int ledPin = 16;
// Variables
bool fireDetected = false;
void setup() {
Serial.begin(115200);
pinMode(photoelectricPin, INPUT_PULLUP); // Assuming normally HIGH with pull-up resistor
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
// Initialize Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
}
void loop() {
// Check photoelectric sensor (button simulation)
fireDetected = digitalRead(photoelectricPin) == LOW; // Simulated LOW when fire detected
if (fireDetected) {
Serial.println("Fire detected!");
// Activate alarm
digitalWrite(buzzerPin, HIGH);
flashLED(); // Flash LED to indicate alarm
// Send data to Google Sheets
sendDataToGoogleSheets();
// Wait to prevent continuous alarms
delay(5000); // 5 seconds delay
} else {
digitalWrite(buzzerPin, LOW);
digitalWrite(ledPin, LOW);
}
}
void flashLED() {
for (int i = 0; i < 5; i++) {
digitalWrite(ledPin, HIGH);
delay(200);
digitalWrite(ledPin, LOW);
delay(200);
}
}
void sendDataToGoogleSheets()
{
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(googleScriptURL);
http.addHeader("Content-Type", "application/json");
// Create JSON payload
DynamicJsonDocument doc(200); // Use DynamicJsonDocument for variable-size JSON
doc["Date"] = getDate();
doc["Time"] = getTime();
doc["Fire Detected"] = "Yes";
String json;
serializeJson(doc, json);
int httpResponseCode = http.POST(json);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi not connected");
}
}
// Dummy functions to simulate date and time
String getDate() {
return "2024-06-30"; // Replace with real date function
}
String getTime() {
return "12:34:56"; // Replace with real time function
}