CNAP
03 / Templates · beginner

PHOTORESISTOR NIGHT LIGHT

Open in Playground

Read an ambient-light sensor and switch an LED on when it gets dark — a classic night-light circuit. The simulator drives the sensor with a slow day/night cycle since there's no physical light to shine on it.

beginnersensoranalog inputserialphotoresistor
Circuit
Code
sketch.inoArduino C++
28 lines
// Photoresistor (LDR) — Light-Triggered Night Light
// Turns the LED on when the simulated ambient light reading drops below
// the threshold, and prints the raw reading to Serial.
// Note: this simulator drives the sensor with a slow day/night cycle
// (no real light source), so the LED will fade in and out on its own —
// on real hardware it reacts to actual ambient light instead.

const int LDR_PIN = A0;
const int LED_PIN = 9;
const int DARK_THRESHOLD = 512; // out of 1023

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int light = analogRead(LDR_PIN);
  bool isDark = light < DARK_THRESHOLD;

  digitalWrite(LED_PIN, isDark ? HIGH : LOW);

  Serial.print("Light level: ");
  Serial.print(light);
  Serial.println(isDark ? "  -> DARK, LED ON" : "  -> BRIGHT, LED OFF");

  delay(300);
}
Components
  • Arduino Uno
    01
  • Photoresistor (LDR)
    02
  • LED (yellow)
    03
  • Resistor 220Ω
    04
Wiring
Component PinArduino Pin
Photoresistor VCC5V
Photoresistor GNDGND
Photoresistor AO (Analog Out)A0
Resistor Pin 1Pin 9
LED Anode (+)Resistor Pin 2
LED Cathode (−)GND