#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char *ssid = ""; // Your WiFi SSID
const char *password = ""; // Your WiFi password
const char *apiKey = "YOUR_THINGSPEAK_API_KEY"; // Thingspeak API Key
const char *server = "api.thingspeak.com";
const int pirPin = 14; // GPIO 14 (D14) for PIR sensor on ESP32
bool alertEnabled = true; // Default alert status
void setup() {
pinMode(pirPin, INPUT);
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Set up Thingspeak
// Note: The Thingspeak library is not needed for the ESP32
// You can use HTTPClient to send data directly
// Connect to Thingspeak TalkBack
talkbackSetup();
}
void loop() {
if (digitalRead(pirPin) == HIGH && alertEnabled) {
Serial.println("Intrusion detected!");
sendDataToThingspeak();
}
delay(5000); // Wait for 5 seconds before checking again
checkTalkBackCommand(); // Check for commands from Thingspeak TalkBack
}
void sendDataToThingspeak() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String data = apiKey;
data += "&field1=" + String(1); // Send value 1 to indicate intrusion
http.begin("http://" + String(server) + "/update");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpResponseCode = http.POST(data);
if (httpResponseCode == 200) {
Serial.println("Data sent to Thingspeak.");
} else {
Serial.println("Error sending data.");
}
http.end();
}
}
void talkbackSetup() {
// Register the device with Thingspeak TalkBack
HTTPClient http;
http.begin("http://" + String(server) + "/talkbacks/YOUR_TALKBACK_ID.json");
int httpResponseCode = http.GET();
if (httpResponseCode == 200) {
String response = http.getString();
Serial.println(response);
}
http.end();
}
void checkTalkBackCommand() {
// Check for commands from Thingspeak TalkBack
HTTPClient http;
http.begin("http://" + String(server) + "/talkbacks/YOUR_TALKBACK_ID/commands/last.json");
int httpResponseCode = http.GET();
if (httpResponseCode == 200) {
String response = http.getString();
Serial.println(response);
if (response.indexOf("alert_on") != -1) {
alertEnabled = true;
Serial.println("Alert enabled.");
} else if (response.indexOf("alert_off") != -1) {
alertEnabled = false;
Serial.println("Alert disabled.");
}
}
http.end();
}