Loading
Loading
IoT Lab content is currently available in Arabic only. We're working on an English version.
عرض بالعربية →How to make your circuit sense darkness to automatically turn on lighting.
Connect LDR between 5V and A0, and connect a 10K resistor between A0 and GND. This is the voltage divider.
const int ldrPin = A0;
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
int lightLevel = analogRead(ldrPin);
Serial.println(lightLevel);
if (lightLevel < 300) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
delay(500);
}Connecting the LDR directly between 5V and A0 without the 10K resistor to ground — the result will always be a fixed reading of 1023 since the voltage won't divide.