
Video
Gambar Rajah Litar

Kod Sumber
1// ─────────────────────────────────────────
2// BlueGrays · bluegrays.com
3// Night Light with Ldr
4// ─────────────────────────────────────────
5// Turns the LED on automatically when it gets dark. The LDR voltage
6// divider is read on A0; when the value drops below 50 (dark) the LED on
7// D13 turns on, and it turns off in the light.
8//
9// Pins:
10// D13 -> LED (with a 330 ohm resistor)
11// A0 -> Junction of the LDR and the 10k resistor
12// LDR other leg to 5V, 10k other leg to GND
13
14int value; // Light reading (0-1023)
15
16void setup() {
17 pinMode(13, OUTPUT); // LED output
18}
19
20void loop() {
21 value = analogRead(A0); // Read the light level
22
23 // Threshold 50: anything below counts as dark. Tune the sensitivity with this number
24 if (value < 50) {
25 digitalWrite(13, HIGH); // Dark: LED on
26 } else {
27 digitalWrite(13, LOW); // Bright: LED off
28 }
29}
30
Soalan Lazim
How do I determine the threshold value?
To see the readings, first add `Serial.begin(9600);` to setup() and `Serial.println(value);` immediately after `value = analogRead(A0);` in loop(), then open the Serial Monitor at 9600 baud. Note the values when the environment is bright and when it is dark. If the wiring produces lower readings in the dark, replace 50 in `if (value < 50)` with a threshold chosen between these two values.
The LED is flickering around the threshold—how can I prevent this?
When the light level is right around the threshold value, small fluctuations cause the LED to turn on and off. If you use two separate thresholds (one for turning on and one for turning off, e.g., 400 and 450)—that is, if you add hysteresis—the flickering disappears.
The LED lights up the LDR and then turns itself off—what should I do?
If the LED's light reaches the LDR, the sensor will detect that the environment is bright. Position the LDR away from the LED or so that it is not facing it; if necessary, build a small shield around the LDR.
Can I light a real candle using this method?
Yes, you can control a 220 V light by connecting a relay module instead of an LED. Mains voltage is dangerous; make the connections while the device is unplugged, and ask an adult or an electrician for help.
