#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const int myChannelNumber = 2504872;
const char* apiKey = "EF0ES2QEMTKHYKRX";
const char* server = "api.thingspeak.com";
const int pirPin = 19; // PIR sensor connected to GPIO 4
void setup() {
Serial.begin(115200);
pinMode(pirPin, INPUT);
connectToWiFi();
}
void loop() {
int pirValue = digitalRead(pirPin);
if (pirValue == HIGH) {
Serial.println("Motion detected!");
sendDataToThingSpeak(1); // Send 1 to ThingSpeak when motion is detected
} else {
Serial.println("No motion detected");
sendDataToThingSpeak(0); // Send 0 to ThingSpeak when no motion is detected
}
delay(5000); // Wait for 5 seconds before checking the PIR sensor again
}
void connectToWiFi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting...");
}
Serial.println("Connected to WiFi");
}
void sendDataToThingSpeak(int motion) {
if ((WiFi.status() == WL_CONNECTED)) {
HTTPClient http;
String url = "http://" + String(server) + "/update?api_key=" + apiKey + "&field1=" + String(motion);
Serial.print("Sending data to ThingSpeak: ");
Serial.println(url);
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error sending data to ThingSpeak. HTTP Error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
}