#include <WiFi.h>
#include <ThingSpeak.h>
const char* ssid = "YOUR_SSID"; // Replace with your Wi-Fi SSID
const char* password = "YOUR_PASSWORD"; // Replace with your Wi-Fi password
const char* apiKey = "V3E4PS0XRGPBCO12"; // Replace with your ThingSpeak Write API Key
const int ldrPin = 0; // LDR connected to analog pin A0
const int pirPin = 12; // PIR sensor connected to digital pin D2
const int ledPin = 5; // LED connected to digital pin D3
WiFiClient client;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(pirPin, INPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
ThingSpeak.begin(client);
}
void loop() {
int ldrValue = analogRead(ldrPin);
int pirValue = digitalRead(pirPin);
// Control LED based on motion and light level
if (pirValue == HIGH) {
if (ldrValue < 300) { // Adjust threshold as needed
analogWrite(ledPin, 255); // Turn on LED
}
} else {
analogWrite(ledPin, 0); // Turn off LED
}
// Send data to ThingSpeak
ThingSpeak.setField(1, ldrValue); // Field 1: LDR Value
ThingSpeak.setField(2, pirValue); // Field 2: PIR Status (0 or 1)
// Write data to ThingSpeak
int x = ThingSpeak.writeFields(2680671, apiKey);
if (x == 200) {
Serial.println("Data sent to ThingSpeak successfully");
} else {
Serial.print("Failed to send data to ThingSpeak. Error code: ");
Serial.println(x);
}
delay(20000); // Send data every 20 seconds
}