Topic 3. Arduino night lamp and button

Code allows you to toggle the LEDs on and off using a button while adjusting their brightness based on the light level sensed by the sensor. The autoTune() function ensures that the LED brightness adapts to varying light conditions efficiently.

Loop:

  • Reads the analog value from the sensor pin (pin 0), which presumably represents the light level.
  • Checks if the button (connected to pin 4) is pressed. If pressed, it toggles the ledState variable between true and false after a debounce delay of 200 milliseconds.
  • If ledState is true, it enters the block to control the LEDs:
    • Calls the autoTune() function to adjust the lightLevel based on the low and high values.
    • Sets the brightness of all three LEDs (ledPin1, ledPin2, ledPin3) using the adjusted lightLevel value.
  • If ledState is false, it turns off all three LEDs.
Arduino code
const int sensorPin = 0;
const int ledPin1 = 12;
const int ledPin2 = 11;
const int ledPin3 = 10;
const int buttonPin = 13; // Assuming the button is connected to digital pin 4

bool ledState = false; // Variable to track the state of LEDs
int low = 1023; // Initialize low and high values for autoTune()
int high = 0;

void setup() {
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP); // Enable internal pull-up resistor
  Serial.begin(9600); // Initialize serial communication
}

void loop() {
  int lightLevel = analogRead(sensorPin); // Read the analog value

  // Check if the button is pressed
  if (digitalRead(buttonPin) == LOW) {
    // If the button is pressed, toggle the LED state
    ledState = !ledState;
    delay(200); // Debouncing delay to prevent rapid toggling
  }

  if (ledState) {
    // If the LED state is true (ON), set the LEDs brightness based on light level
    autoTune(lightLevel); // Adjust lightLevel using autoTune()
    analogWrite(ledPin1, lightLevel);
    analogWrite(ledPin2, lightLevel);
    analogWrite(ledPin3, lightLevel);
  } else {
    // If the LED state is false (OFF), turn off the LEDs
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
  }

  Serial.println(lightLevel); // Print the light level to serial monitor
  delay(1000); // Delay for stability
}

void autoTune(int &lightLevel) {
   if (lightLevel < low)  
  {                      
    low = lightLevel;   
  }
  if (lightLevel > high)
  {
    high = lightLevel;
  }
  lightLevel = map(lightLevel, low+10, high-30, 0, 255);
  lightLevel = constrain(lightLevel, 0, 255);
}