#include <WiFi.h>
#include <HTTPClient.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#define PIR_PIN 2 // Pin connected to PIR sensor output
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Google Apps Script Web App URL
const char* serverName = "https://script.google.com/macros/s/AKfycbzCj1km4x9hOq4BPCiwO-nOr8GNfSvihVfSaoJ1IO_gjSw6_ujM1zJwT7n-_66oed8p/exec"; // Replace "URL" with your Google Apps Script URL
// Initialize WiFi and NTP client
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 7200, 60000); // UTC+2 offset, update every 60 sec
void setup() {
Serial.begin(115200);
// Setup WiFi connection
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize NTP client
timeClient.begin();
timeClient.update();
// Set PIR sensor as input
pinMode(PIR_PIN, INPUT);
}
void loop() {
if (WiFi.status() == WL_CONNECTED) { // Check if ESP32 is connected to WiFi
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/json");
// Fetch time from NTP client
timeClient.update();
String formattedTime = timeClient.getFormattedTime();
// Get PIR sensor data
int motionDetected = digitalRead(PIR_PIN); // HIGH if motion is detected, LOW otherwise
// Prepare JSON payload with NTP time and motion status
String jsonData = "{\"method\":\"append\", \"motion\":" + String(motionDetected) +
", \"timestamp\":\"" + formattedTime + "\" }";
// Send HTTP POST request
int httpResponseCode = http.POST(jsonData);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.println("Error on sending POST: " + String(httpResponseCode));
}
http.end(); // Close connection
} else {
Serial.println("WiFi Disconnected");
}
delay(3000); // General loop delay
}