Light Sensor

In this project, you'll learn how to use a light sensor to automatically turn on and off a LED.

A photo resistor is used to sense the amount of light in a room. A LED is automatically turned on when the room is dark and turned off when it is bright. This is accomplished by connecting a photo resistor to one of the analog input pins on the Arduino. There are six analog input pins on the Arduino board, and are labeled A0 to A5.

Parts needed:
  • Arduino
  • A photo resistor
  • A 22K Ω resistors (red-red-orange)
  • Wires
  • Breadboard
Photo resistor      22K ohm resistor
1 Making the connections
  • Connect one end of the photo resistor to positive 5V on the Arduino.
  • Connect the other end of the photo resistor to pin A0 on the Arduino and to one end of the 22K Ω resistor.
  • Connect the other end of the resistor to GND on the Arduino board.
Light sensor schematic
Light sensor connections
2 Create a new Bare Minimum program by selecting File from the menu
  • then select Examples
  • then select Basics
  • then select BareMinimum

Then type in this program.

The Serial.begin command prepares the serial monitor for printing outputs. The number 9600 is the speed at which the monitor will communicate at.

The analogRead command reads in an analog value (a number between 0 and 1023) from the specified analog input pin. This number is assigned and stored in the sensorValue variable.

The Serial.println command prints out the number that is stored in the sensorValue variable to the monitor.
Light sensor program
3 Open the serial monitor by clicking on the Serial Monitor icon. Serial monitor icon
4 Make sure that the baud rate (number at the bottom right corner of the monitor) matches the number specifed in the Serial.begin command. In this case, it is 9600. Monitor output
5 Run the program and notice the numbers being printed in the serial monitor.

The numbers get smaller when you cover the photo resistor with your hand, and gets larger when you move your hand away.

From the numbers listed in the monitor, we see that a good cut off value between light and dark is 600.
6 Modify the program to this and run it.

The photo resistor is connected to pin A0 on the Arduino board.

We will use the internal LED that is connected to pin 13 on the Arduino board.

The if command checks the sensorValue to see if it is < 600. If sensorValue is less than 600 then the first digitalWrite command is executed to turn on the LED,

otherwise the second digitalWrite command in the else part of the if command is executed to turn off the LED.
Light sensor program