#include <WiFiConnect.h>
#include <ThingSpeak.h>
WiFiClient client;
long myChannelNumber = 2715044;
const char * myWriteAPIKey = "J9WP1F0FD8B02WBSY";
int statusCode;
char ssid[] = "WOKWI-GUEST";
char pass[] = "";
const int ldrPin = 34; // LDR connected to GPIO 34 (Analog)
const int pirPin = 14; // PIR sensor connected to GPIO 14
const int ledPin = 23; // LED connected to GPIO 23
void setup() {
pinMode(ledPin, OUTPUT); // Set LED pin as OUTPUT
pinMode(pirPin, INPUT); // Set PIR pin as INPUT
Serial.begin(115200); // Start Serial for debugging
WiFiConnect.begin(ssid, pass);
while (WiFiConnect.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFiConnect");
ThingSpeak.begin(client);
}
void loop() {
int ldrValue = analogRead(ldrPin); // Read LDR value
int pirState = digitalRead(pirPin); // Read PIR sensor state
// Check if it's dark enough (adjust threshold based on testing)
if (ldrValue < 2000) { // Adjust threshold based on testing
if (pirState == HIGH) {
digitalWrite(ledPin, HIGH); // Turn ON the LED
Serial.println("LED ON - Motion detected in dark");
} else {
digitalWrite(ledPin, LOW); // Turn OFF the LED if no motion
Serial.println("LED OFF - No motion");
}
} else {
digitalWrite(ledPin, LOW); // Turn OFF the LED if it's bright
Serial.println("LED OFF - It's bright");
}
// Send data to ThingSpeak fields
ThingSpeak.setField(1, ldrValue); // Field 1 for LDR value
ThingSpeak.setField(2, pirState); // Field 2 for PIR state
// Write data to ThingSpeak
statusCode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (statusCode == 200) {
Serial.println("Data sent to ThingSpeak successfully");
} else {
Serial.println("Problem sending data. HTTP error code: " + String(statusCode));
}
delay(10000); // Delay of 10 seconds before repeating the loop
}