// Pin assignments
const int pirPin = 2; // PIR sensor output pin
const int ldrPin = A0; // LDR analog input pin
const int relayPin = 5; // Relay Pin
// Threshold values
int ldrThreshold = 300; // Threshold for the LDR
int pirState = LOW; // Initial state of PIR sensor
int pirValue = 0; // PIR sensor value
void setup() {
pinMode(pirPin, INPUT); // PIR sensor as input
pinMode(relayPin, OUTPUT); // Relay as output
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Read PIR sensor value
pirValue = digitalRead(pirPin);
// Read LDR value (light level)
int ldrValue = analogRead(ldrPin);
// Print LDR and PIR values (for debugging)
Serial.print("LDR Value: "+String(ldrValue));
Serial.print(" | PIR Value: "+String(pirValue));
// If PIR detects motion and ambient light level is low, turn on the Relay
if (pirValue == HIGH && ldrValue < ldrThreshold) {
digitalWrite(relayPin, HIGH); // Turn on the Relay
Serial.println(" | RELAY ON");
}
// If no motion or ambient light is high, turn off the Relay
else {
digitalWrite(relayPin, LOW); // Turn off the Relay
Serial.println(" | RELAY OFF");
}
delay(500); // Short delay to avoid bouncing
}