// Pin definitions
const int buttonPin = 5;
const int ledPin = 6;
const int ldrPin = A3;
// Variables for button state and LED toggle
int buttonState = 0;
int lastButtonState = 0;
int ledState = LOW; // Start with LED off
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
checkButton(); // Check if the button is pressed and toggle the state
updateLED(); // Update LED state based on button and LDR when LED is ON
delay(100); // Short delay for stability
}
// Function to check the button press and toggle LED state
void checkButton() {
buttonState = digitalRead(buttonPin);
// Toggle LED state on button press
if (buttonState == HIGH && lastButtonState == LOW) {
ledState = !ledState; // Toggle the LED state
}
lastButtonState = buttonState;
}
// Function to update LED brightness based on the LDR when LED is ON
void updateLED() {
// If the LED is turned ON by the button
if (ledState == HIGH) {
int ldrValue = analogRead(ldrPin); // Read the LDR value (0-1023)
// Map the LDR value to PWM range (0-255) for brightness control
int brightness = map(ldrValue, 0, 1023, 0, 255); // Darker = brighter
// Apply the brightness to the LED using PWM
analogWrite(ledPin, brightness);
// Debugging output
Serial.print("LDR Value: ");
Serial.print(ldrValue);
Serial.print(" | LED Brightness: ");
Serial.println(brightness);
} else {
// If the LED is OFF, ensure it's completely off
analogWrite(ledPin, 0);
Serial.println("LED OFF.");
}
}