Lesson 13: A smart night light
Trang này cần trình duyệt gần đây (hỗ trợ SharedArrayBuffer). Vui lòng cập nhật Chrome, Edge, Firefox hoặc Safari lên phiên bản mới nhất.
English
A light that thinks
- A street light switches on by itself when it gets dark. Inside there is a light sensor.
- In lessons 7 and 8 a knob gave the voltage and
mapset the brightness. Now you build the sensor circuit yourself, and the light controls the LED. - You build one with an LDR: its resistance is small in bright light and very big in the dark.
- With a 10 kΩ resistor it makes a potential divider, so the voltage on A0 follows the light.
analogRead(A0)gives 0 to 1023.
Words for this lesson
| Word | Meaning |
|---|---|
| LDR | light-dependent resistor: a resistor that reacts to light |
| potential divider | two resistors in a line; the middle point gets part of the voltage |
| PWM | switching a pin on and off very fast, so an LED looks dimmer |
| map | change a number from one range into another range |
| mood | here: a way the light behaves (off, soft, full) |
English
From a reading to a brightness
analogWrite(9, value)takes 0 (off) to 255 (full). The reading is 0 to 1023, so it needs changing.map(light, 0, 1023, 255, 0)does it. Bright (1023) gives 0, dark (0) gives 255:
| Light | analogRead(A0) |
map(…, 0, 1023, 255, 0) |
LED |
|---|---|---|---|
| bright day | 984 | 10 | almost off |
| cloudy | 627 | 99 | about 40 % |
| night | 92 | 233 | almost full |
- The formula inside
mapis: brightness = 255 − light × 255 ÷ 1023. Try a reading: 627 × 255 ÷ 1023 ≈ 156, and 255 − 156 = 99.
English
Watch the numbers
void setup() {
Serial.begin(9600);
}
void loop() {
int light = analogRead(A0);
Serial.print("Light: ");
Serial.print(light);
Serial.print(" LED: ");
Serial.println(map(light, 0, 1023, 255, 0));
delay(500);
}
- Run it and move the knob for A0. The Serial Monitor shows the reading and the brightness side by side.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Build the light sensor: LDR from 5V to A0, and 10 kΩ from A0 to GND. Put an LED with a 220 Ω resistor on pin 9. Then make the LED brighter when it gets darker: change the reading 0–1023 into a brightness 255–0 with map, and send it to pin 9 with analogWrite. Move the light slider while it runs.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Give the light three moods. Day (reading above 700): LED off. Evening (300 to 700): a soft glow, analogWrite(9, 40). Night (below 300): full power, 255. Use if, else if và else.
Nhấn Chạy để xem kết quả ở đây.