#include <WiFi.h>
#include <HTTPClient.h>
#define MQ2_PIN 34
#define PIR_PIN 27
#define BUZZER_PIN 25
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String apiKey = "93GE1UU25BKIOK1U"; // Your ThingSpeak Write API Key
void setup() {
Serial.begin(115200);
pinMode(MQ2_PIN, INPUT);
pinMode(PIR_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Connected");
}
void loop() {
int gasValue = analogRead(MQ2_PIN);
int motionValue = digitalRead(PIR_PIN);
Serial.println("--------------------");
Serial.print("Gas Value: ");
Serial.println(gasValue);
Serial.print("Motion: ");
Serial.println(motionValue);
// Alarm Condition
if (gasValue > 2000 || motionValue == 0) {
Serial.println("ALERT! Buzzer ON");
digitalWrite(BUZZER_PIN, HIGH);
delay(500);
digitalWrite(BUZZER_PIN, LOW);
delay(500);
} else {
digitalWrite(BUZZER_PIN, LOW);
Serial.println("System Normal");
}
// Send Data to ThingSpeak
HTTPClient http;
String url =
"https://api.thingspeak.com/update?api_key=" + apiKey +
"&field1=" + String(gasValue) +
"&field2=" + String(motionValue);
http.begin(url);
int httpCode = http.GET();
Serial.print("ThingSpeak Response: ");
Serial.println(httpCode);
String payload = http.getString();
Serial.print("Entry Number: ");
Serial.println(payload);
http.end();
delay(15000); // ThingSpeak minimum update interval
}