#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* server = "api.thingspeak.com";
const String apiKey = "MXGOA0407N1FIBGC";
const int pirPin = 2;
void setup() {
Serial.begin(115200);
pinMode(pirPin, INPUT);
connectToWiFi();
}
void loop() {
int pirValue = digitalRead(pirPin);
if (pirValue == HIGH) {
Serial.println("Motion detected!");
sendToThingSpeak(1);
} else {
Serial.println("No motion detected.");
sendToThingSpeak(0);
}
delay(5000);
}
void connectToWiFi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void sendToThingSpeak(int motion) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "http://" + String(server) + "/update?api_key=" + apiKey + "&field1=" + String(motion);
Serial.println("Sending to ThingSpeak: " + url);
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode == 200) {
Serial.println("Data sent to ThingSpeak successfully");
} else {
Serial.print("Error sending data to ThingSpeak. HTTP error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected. Cannot send data to ThingSpeak.");
}
}