#include <WiFi.h> // Wi-Fi library for ESP32
#include <HTTPClient.h> // HTTP client to send requests
#include <ThingSpeak.h>
const char* ssid = "Wokwi-GUEST"; // Replace with your Wi-Fi SSID
const char* password = ""; // Replace with your Wi-Fi password
String apiKey = "QSN6LM0N6TZIDQQL"; // Replace with your ThingSpeak API key
//New code added up..
WiFiClient client;
unsigned long myChannelNumber = 1;
const char * myWriteAPIKey = "QSN6LM0N6TZIDQQL";
//New code added up..
int pirPin = 15; // PIR sensor OUT pin connected to GPIO15
int ledPin = 2; // LED connected to GPIO2 (ESP32 built-in LED)
bool motionDetected = false;
void setup() {
Serial.begin(115200);
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.println("PIR Sensor Test Started...");
//New code (Might remove)
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
//Newcode (Might remove)
// Connect to Wi-Fi (Newly added code)
WiFi.begin(ssid, password, 6);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
Serial.println("Connected to WiFi"); // Newly added Code ends here
}
void loop() {
int pirState = digitalRead(pirPin); // Read PIR sensor output
if (pirState == HIGH) { // Motion detected
if (!motionDetected) {
motionDetected = true;
digitalWrite(ledPin, HIGH); // Turn on LED
Serial.println("Motion detected!");
// Trigger camera and cloud upload
}
} else {
if (motionDetected) {
motionDetected = false;
digitalWrite(ledPin, LOW); // Turn off LED
Serial.println("Motion ended");
}
}
delay(1000);
// Send data to ThingSpeak (Newly added code)
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// ThingSpeak API endpoint
String url = "http://api.thingspeak.com/update?api_key=" + apiKey + "&field1=" + String(motionDetected);
http.begin(url); // Initiate HTTP connection
int httpResponseCode = http.GET(); // Send HTTP GET request
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode); // Print HTTP response code
Serial.println(response); // Print server response
} else {
Serial.println("Error in sending request");
}
http.end(); // Close connection
}
delay(20000); // Send data every 20 seconds (Newly added code ends here)
}