#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* server = "api.thingspeak.com";
const char* apiKey = "TGRXPY7QEBTWUQKN";
#define PIR_PIN 6
#define LED_PIN 7
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
int motionDetected = digitalRead(PIR_PIN);
if (motionDetected) {
Serial.println("Motion detected!");
digitalWrite(LED_PIN, HIGH);
sendDataToThingSpeak(1);
} else {
Serial.println("No motion detected");
digitalWrite(LED_PIN, LOW);
}
delay(1000);
}
void sendDataToThingSpeak(int motion) {
if ((WiFi.status() == WL_CONNECTED)) {
HTTPClient http;
String url = "http://";
url += server;
url += "/update?api_key=";
url += apiKey;
url += "&field1=";
url += 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();
}
}