Zed-King Institute

    Arduino LDR Automatic Night Lamp

    mediumAnalog inputArduino (C++)

    A light-dependent resistor changes with light; comparing its reading to a threshold makes an automatic lamp.

    The question

    An LDR (light sensor) is on A2 and an LED on pin 2. Turn the LED ON when the reading is below 400 (dark) and OFF otherwise.

    The sketch

    sketch.ino

    void setup() {
      pinMode(2, OUTPUT);
    }
    
    void loop() {
      int light = analogRead(A2);
      if (light < 400) {
        digitalWrite(2, HIGH);
      } else {
        digitalWrite(2, LOW);
      }
    }

    Wiring

    LDR module: VCC → 5V, GND → GND, AO → A2. LED → 220Ω → pin 2.

    How it works

    1. 1analogRead() gives a lower number when it is darker (with the usual LDR module wiring).
    2. 2If the reading is below the threshold, it is dark — turn the LED on.
    3. 3Otherwise turn it off. The threshold is tuned by watching the readings.

    Common mistakes

    • Using the wrong comparison direction for your module — some modules read higher in the dark.
    • Choosing a threshold without printing the readings first.

    Now solve a similar question yourself

    A new Arduino question every time, checked instantly.

    Practice questions

    More in Analog input