Write a program to interface LDR with Arduino and put on /off the light according to outside darkness /brightness.
Last Updated : 15 Jul 2025
Jan 22, Jul 24
Solution:
const int ldrpin = A2; // Define the pin for the LDR (Light Dependent Resistor)
const int ledpin = 10; // Define the pin for the LED
void setup() {
pinMode(ledpin, OUTPUT); // Set LED pin as an output
}
void loop() {
int reading = analogRead(ldrpin); // Read the LDR value
if (reading < 200) { // If the LDR value is below 200
digitalWrite(ledpin, HIGH); // Turn the LED on
} else {
digitalWrite(ledpin, LOW); // Otherwise, turn the LED off
}
delay(1000); // Wait for 1 second before the next reading
}
OUTPUT Description:
In Low Light Conditions:
The LED will be ON if the environment is dark enough (LDR reading < 200).
In Bright Light Conditions:
The LED will be OFF if there is sufficient light (LDR reading ≥ 200).
Code Explaination:
-
Pin Definitions:
ldrpin
(A2): Connects to the LDR.ledpin
(10): Connects to the LED.
-
Setup (
setup
function):- Sets
ledpin
as an output.
- Sets
-
Main Loop (
loop
function):- Reads light level from
ldrpin
. - Turns the LED ON if light level is below 200; otherwise, turns it OFF.
- Waits 1 second before the next check.
- Reads light level from
Meanwhile you can watch this video
Watch Video