Switch a light on at dusk and off at dawn, with a little hysteresis so it never flickers.
Guide
An LDR (light-dependent resistor) and a fixed 10 kΩ resistor form a voltage divider. As the light changes, the voltage between them changes, and the Arduino reads it on an analog pin as a number from 0 to 1023.
7 parts · about ₹993
What you need
Safety first: build and test with an LED or a 12 V lamp. Only switch mains (230 V) once you understand relay wiring, inside a closed box, with the power off while you work.
Step 1 of 4
Milestone
Sensor reads light
Covering the LDR with your finger makes the Serial Monitor number drop.
Step 2 of 4
Step 3 of 4
| 1 | const int LDR = A0, RELAY = 7; |
| 2 | const int DARK = 300; // turn ON below this |
| 3 | const int BRIGHT = 400; // turn OFF above this (the gap stops flicker at dusk) |
| 4 | const bool RELAY_ACTIVE_LOW = true; // most relay boards: LOW = on. Set false if yours is the other way |
| 5 | |
| 6 | bool lightOn = false; |
| 7 | |
| 8 | void setLight(bool on) { |
| 9 | digitalWrite(RELAY, (on != RELAY_ACTIVE_LOW) ? HIGH : LOW); |
| 10 | } |
| 11 | |
| 12 | void setup() { |
| 13 | pinMode(RELAY, OUTPUT); |
| 14 | setLight(false); |
| 15 | Serial.begin(9600); |
| 16 | } |
| 17 | |
| 18 | void loop() { |
Watch the numbers in the Serial Monitor in your real room at dusk and set DARK and BRIGHT either side of them.
Milestone
Switches at dusk
Covering the LDR clicks the relay on; uncovering it clicks it off, with no chatter in between.
Step 4 of 4
With a single threshold, a reading that wobbles around it (clouds, a passing car) would switch the light on and off many times a second. Two thresholds with a gap between them, called hysteresis, mean it only changes state when the light has really changed.
Labs
All labs