// Pins
const int lightSensorPin = 2; // digital photoresistor pin
const int ledPin = 9;
const int buttonPin = 7;
const int buzzerPin = 8;
// State
bool ledOn = true;
// Debounce
int lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;
void setup() {
// Pin modes
pinMode(buttonPin, INPUT_PULLUP); // button to GND
pinMode(lightSensorPin, INPUT); // digital photoresistor
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
digitalWrite(ledPin, HIGH); // start LED ON
ledOn = true;
}
void loop() {
// ---- Button handling (toggle LED) ----
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
static int stableButtonState = HIGH;
if (reading != stableButtonState) {
stableButtonState = reading;
if (stableButtonState == LOW) {
// button pressed -> toggle LED
ledOn = !ledOn;
digitalWrite(ledPin, ledOn ? HIGH : LOW);
}
}
}
lastButtonState = reading;
// ---- Light sensor + buzzer ----
if (!ledOn) {
// LED OFF => sensor disabled, buzzer OFF
noTone(buzzerPin);
} else {
// LED ON => allow sensor to control buzzer
int lightState = digitalRead(lightSensorPin);
// Adjust this depending on wiring:
// If using pull-up: bright -> LOW, dark -> HIGH
// If using external divider: bright -> HIGH, dark -> LOW
bool brightDetected = (lightState == LOW);
if (brightDetected) {
tone(buzzerPin, 1000); // buzzer ON
} else {
noTone(buzzerPin); // buzzer OFF
}
}
delay(20);
}