
วิดีโอ
แผนผังวงจร

ซอร์สโค้ด
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
FAQ
กำหนดค่าเกณฑ์อย่างไร
หากต้องการดูค่าที่วัดได้ ให้เพิ่ม `Serial.begin(9600);` ใน setup() และเพิ่ม `Serial.println(value);` ต่อจาก `value = analogRead(A0);` ทันทีใน loop() แล้วเปิด Serial Monitor ที่ 9600 บอด จดค่าที่ได้ตอนสว่างและตอนทำให้มืด หากต่อวงจรแบบที่ค่าอ่านได้ลดลงเมื่อมืด ให้แทน 50 ใน `if (value < 50)` ด้วยค่าเกณฑ์ที่เลือกไว้ระหว่าง 2 ค่านั้น
LED กะพริบเมื่อค่าแสงใกล้ค่าเกณฑ์ ป้องกันอย่างไร
เมื่อระดับแสงอยู่ใกล้ค่าเกณฑ์ ความผันผวนเล็กน้อยจะทำให้ LED ติดๆ ดับๆ หากใช้ค่าเกณฑ์แยกกันสำหรับเปิดและปิด เช่น 400 และ 450 หรือที่เรียกว่าการเพิ่มฮิสเทอรีซิส ก็จะช่วยหยุดอาการกะพริบได้
แสงจาก LED ส่องโดน LDR แล้วทำให้ไฟดับเอง ควรทำอย่างไร
หากแสงจาก LED ส่องถึง LDR เซ็นเซอร์จะเข้าใจว่าบริเวณนั้นสว่าง ให้วาง LDR ห่างจาก LED หรือหันไปทางอื่น หากจำเป็นให้ทำแผ่นบังแสงเล็กๆ รอบ LDR
ใช้วิธีนี้เปิดหลอดไฟจริงได้ไหม
ได้ ใช้โมดูลรีเลย์แทน LED เพื่อควบคุมหลอดไฟ 220 V ไฟบ้านมีอันตราย ให้ถอดปลั๊กอุปกรณ์ก่อนต่อสายและขอความช่วยเหลือจากผู้ใหญ่หรือช่างไฟฟ้า
