const int pirPin = 2; // PIR sensor pin
const int ldrPin = A0; // LDR sensor pin
const int relayPin = 3; // Relay pin for controlling the light bulb
int lightThreshold = 400; // Adjust this value based on your room's lighting conditions
bool motionDetected = false; // Flag to track motion detection
void setup() {
pinMode(pirPin, INPUT);
pinMode(relayPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int pirValue = digitalRead(pirPin); // Read PIR sensor
int ldrValue = analogRead(ldrPin); // Read LDR sensor
if (pirValue == HIGH) {
Serial.println("Motion detected! Turning on light...");
motionDetected = true;
} else {
Serial.println("No motion detected. Turning off light...");
motionDetected = false;
}
if (motionDetected) {
if (ldrValue < lightThreshold) {
// If it's dark in the room, turn on the light bulb fully
digitalWrite(relayPin, HIGH);
} else {
// If it's bright in the room, dim the light bulb
int brightness = map(ldrValue, lightThreshold, 1023, 0, 255); // Map LDR value to PWM range (0-255)
analogWrite(relayPin, brightness); // Set brightness of the light bulb
}
} else {
// If no motion detected, turn off the light bulb
digitalWrite(relayPin, LOW);
}
delay(1000); // Adjust the delay as needed
}