Photocell and LED Example

Photocell and LED

Let's control an LED using a photoresistor! 
We are going to control an LED brightness along with the light that a photoresistor receives. 
The more is the light that the photoresistor receives, the more the LED brightness will be.

Hardware

  • LDR photocell
  • 10K Ohm
  • 220 Ohm
  • LED

Circuit

Photocell and led circuit 
The LED is connected to PIN 11, and between this link there's a resistor. 
The photoresistor is connected to 5V and Ground respectively. The ground has also a resistor connected to it. 
Then link the Ground PIN of the resistor to the Analog Input 0. 
The Fritzing circuit here should clarify everything.

Schematic

Phtocell and led schematic

Code

The sketch reads the light received by the photoresistor and it converts it to a value usable to light the Led. 
The value is converted in order to light the led (from an input between 0-1023 to an output of 0-255)

 
 
//Define the photoresistor PIN (A0)
int photocellPin = 0;
 
//This variable will contain the raw value read from photoresistor
int photocellReading;
 
//Define the LED PIN 11 (PWM)
int LEDpin = 11;
 
//This variable contains the brightness of the LED
int LEDbrightness;
 
void setup(void) {
}
 
void loop(void) {
//Read the value from ptohoresistor
photocellReading = analogRead(photocellPin);
 
//Map the ptohoresistor reading to 0,255
//to set correctly the LED brightness
LEDbrightness = map(photocellReading, 0, 1023, 0, 255);
 
//Set the LED brightness
analogWrite(LEDpin, LEDbrightness);
 
delay(50);
}