This is a simple Arduino UNO project that can turn on and off the LED light with push button or light censor.
The push button is perfectly working it turns on and off the LED light without any problem. The light censor is working too, I debugged it and it can detect light. My problem is even though the light level is more than the threshhold, it still does not turn the LED on or off like no effect.
Here is my Arduno diagram. Arduino Diagram
And Here is my code.
int ledPin = 13; // LED connected to digital pin 13
int lightSensorPin = A0; // Photoresistor connected to analog pin A0
int btnPin = 2; // Button connected to digital pin 2
int threshold = 400; // Light level threshold (adjust based on your sensor and environment)
int state = LOW; // Current state of the LED
void setup() {
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
pinMode(btnPin, INPUT_PULLUP); // Set the button pin as input with an internal pull-up resistor
Serial.begin(9600); // Initialize serial communication for debugging
}
void loop() {
int lightLevel = analogRead(lightSensorPin); // Read the light sensor value
int buttonState = digitalRead(btnPin); // Read the button state
// Debugging: Print the light sensor value and button state
Serial.print("Light Level: ");
Serial.print(lightLevel);
Serial.print(" | Button State: ");
Serial.println(buttonState);
// Toggle LED state when button is pressed
if (buttonState == LOW) { // Button pressed (active LOW)
delay(50); // Debounce delay
if (digitalRead(btnPin) == LOW) { // Confirm button is still pressed
state = !state; // Toggle the state
digitalWrite(ledPin, state); // Update the LED
while (digitalRead(btnPin) == LOW) {
// Wait for button release to avoid multiple toggles
}
}
}
else {
// Control LED based on light sensor only if the button is not pressed
if (lightLevel < threshold) {
digitalWrite(ledPin, LOW); // Turn on the LED if light level is below the threshold
} else {
digitalWrite(ledPin, HIGH); // Turn off the LED if light level is above the threshold
}
}
delay(100); // Small delay to smooth the sensor readings
}