Auto Sensing Light
A photoresistor is a semiconductor component which changes its resistance depending on the ambient light. As more photons from ambient light hit the photoresistor, more free electrons get available to conduct electricity. These photoresistors are also called light dependent resistors (LDR).
In this project we will read the input from a photoresistor to determine ambient light level and switch an LED on when it is too dark.
The amount of resistance is an analog value which we can read using analog I/O pins on microcontroller. As we learned from the project of analog input using potentiometer, the reading from analog pins is converted into a digital by ADC incorporated in the microcontroller board. The ADC converts analog signal into 10 bit digital signal which means there are 210 = 1024 levels of the input data.
When the value from LDR goes below some threshold, we will switch the LED on. If the value goes above the threshold we will switch the LED off.

Components
Connections
Connect the battery block Vs pin to the Vs pin of the microcontroller block. Connect any of black (negative) pins on the battery block to one of the negative (black) pin on the microcontroller block.

Connect the red and black terminal of photoresistor block to 5V and negative pins on battery block respectively. Connect the photoresistor blue terminal to microcontroller A0 pin.
Connect the red terminal of the LED block to the microcontroller pin D6. Connect the black terminal of the LED block to the negative (black) pin of battery block.
Code
/*
Makernova Robotics 2025
In this program we use a photoresistor to detect ambient light
and decide to switch the LED on if the ambient light is low
The LED remains off if ambient light is sufficient
*/
int ledPin = 6; // declare D6 as LED pin
int ldrPin = A0; // declare A0 as pin to read LDR
void setup() {
// Initializing LED pins as output & LDR pin as input
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
}
void loop() {
//read value of LDR in variable ldrValue
int ldrValue = analogRead(ldrPin);
// The value is read on scale 0 to 1023.
// Higher the light, higher is the reading
// Check if the input value is below a threshold value
if (ldrValue < 400) { //adjust this threshold value as necessary
digitalWrite(ledPin, HIGH); // switch the LED on
}
// runs if the input value is not below threshold value
else {
digitalWrite(ledPin, LOW); // switch the LED off
}
delay(200); // wait for 200ms before running the loop again
}


