#include <WiFi.h> // WiFi library for ESP32
// #include <ESP8266WiFi.h> // WiFi library for ESP32
#include "ThingSpeak.h" // ThingSpeak library for sending data to the cloud
// Define pins
#define PIR_SENSOR_PIN 7 // Digital input pin for the PIR motion sensor
#define LDR_SENSOR_PIN 34 // Analog input pin for the LDR (photoresistor)
// WiFi credentials (Wokwi guest network has no password)
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Create a WiFiClient object for ThingSpeak communication
WiFiClient client;
// ThingSpeak configuration
unsigned long channelID = 2930049; // ThingSpeak Channel ID
const char* writeAPIKey = "3SQBNN8AL2DX2MUD"; // ThingSpeak Write API Key
void setup() {
// Initialize serial communication for debugging
Serial.begin(115200);
// Configure the PIR sensor pin as input
pinMode(PIR_SENSOR_PIN, INPUT);
// Connect to WiFi
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print("."); // Print dots while waiting
}
Serial.println("\nWiFi connected");
// Initialize ThingSpeak with the WiFi client
ThingSpeak.begin(client);
}
void loop() {
// Read motion detection value from PIR sensor (0 = no motion, 1 = motion)
int pirValue = digitalRead(PIR_SENSOR_PIN);
// Read analog value from LDR (light intensity)
int rawLdrValue = analogRead(LDR_SENSOR_PIN);
// Constrain the LDR value to a practical range to avoid outliers
rawLdrValue = constrain(rawLdrValue, 32, 4063);
// Map the LDR analog value (from 32 to 4063) to a luminosity scale (0 to 100000)
// Higher raw value = darker environment → lower luminosity
float luminosity = (4063 - rawLdrValue) * (100000.0 / (4063 - 32));
// Print sensor data to the Serial Monitor for debugging and validation
Serial.print("PIR Value: ");
Serial.print(pirValue);
Serial.print(" | Raw LDR: ");
Serial.print(rawLdrValue);
Serial.print(" | Mapped Luminosity: ");
Serial.println((int)luminosity);
// Prepare data fields for ThingSpeak
ThingSpeak.setField(1, pirValue); // Field 1: PIR motion status
ThingSpeak.setField(2, (int)luminosity); // Field 2: Mapped luminosity value
// Send data to ThingSpeak channel
int x = ThingSpeak.writeFields(channelID, writeAPIKey);
// Check if data was sent successfully
if (x == 200) {
Serial.println("Data sent to ThingSpeak successfully.");
} else {
Serial.print("Error sending data: ");
Serial.println(x); // Error code helps with debugging
}
// Wait 15 seconds before next upload
delay(15000);
}