// Pin definitions
#define PIR_PIN 26 // PIR sensor pin (motion detection)
#define LDR_PIN 34 // LDR sensor pin (ambient light detection, must be an analog-capable pin on ESP32)
#define LIGHT_PIN 25 // Light control pin (for LED or relay to control a light)
// Thresholds and timeout settings
const int lightThreshold = 500; // Adjust based on ambient light level needed to turn on the light
const unsigned long motionTimeout = 10000; // 30 seconds without motion to turn off light
// Variables for tracking state
unsigned long lastMotionTime = 0; // Last time motion was detected
bool lightOn = false; // Track if the light is currently on
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT); // Set PIR sensor as input
pinMode(LDR_PIN, INPUT); // Set LDR sensor as input
pinMode(LIGHT_PIN, OUTPUT); // Set light control pin as output
digitalWrite(LIGHT_PIN, LOW); // Start with light turned off
Serial.println("Smart Light System Initialized");
}
void loop() {
// Read the PIR sensor to detect motion
int pirState = digitalRead(PIR_PIN);
// Read the LDR sensor for ambient light level
int ldrValue = analogRead(LDR_PIN);
// Print readings to Serial Monitor
Serial.print("PIR State: ");
Serial.print(pirState);
Serial.print(" | LDR Value: ");
Serial.println(ldrValue);
// Check if motion is detected and ambient light is below threshold
if (pirState == HIGH && ldrValue < lightThreshold) {
lastMotionTime = millis(); // Update last motion detection time
if (!lightOn) {
digitalWrite(LIGHT_PIN, HIGH); // Turn on the light
lightOn = true;
Serial.println("Light ON");
}
}
// Check if the light should be turned off due to no motion
if (lightOn && (millis() - lastMotionTime > motionTimeout)) {
digitalWrite(LIGHT_PIN, LOW); // Turn off the light
lightOn = false;
Serial.println("Light OFF");
}
delay(500); // Adjust delay as needed
}