CODE
const int ldrPin = A0; // LDR connected to analog pin A0
const int buzzerPin = 8; // Buzzer connected to digital pin 8
const unsigned long buzzerDuration = 50; // Buzzer activation duration in milliseconds (5 seconds)
unsigned long lastBuzzerTime = 0; // Variable to store the last time the buzzer was activated
void setup() {
pinMode(buzzerPin, OUTPUT);
digitalWrite(buzzerPin, LOW); // Initially turn off buzzer
}
void loop() {
int ldrValue = analogRead(ldrPin);
// Adjust the threshold based on your LDR and ambient light conditions
// Higher values mean more light is hitting the LDR
if (ldrValue > 50) {
// Check if it's time to activate the buzzer again
if (millis() - lastBuzzerTime >= buzzerDuration) {
digitalWrite(buzzerPin, HIGH); // Turn on buzzer
delay(1000000); // Delay to ensure buzzer stays on for 100ms
digitalWrite(buzzerPin, LOW); // Turn off buzzer
lastBuzzerTime = millis(); // Update last buzzer activation time
}
} else {
digitalWrite(buzzerPin, LOW); // Turn off buzzer when no light is detected
}
// Add a delay to prevent rapid checking and to stabilize readings
delay(10); // Adjust delay time as needed
}