Introduction: Photoresistor (Analog Input)

About: Learn electronics with Tinkercad Circuits!

Let's learn how to read a photoresistor, a light-sensitive type of variable resistor, using Arduino's Analog Input. It's also called an LDR (light-dependent resistor).

So far you've already learned to read a potentiometer, which is another type of variable resistor, so we'll build on those skills in this lesson. Remember that Arduino's analog inputs (pins marked A0-A6) can detect a gradually changing electrical signal, and translates that signal into a number between 0 and 1023.

  1. Explore the sample circuit here in the workplane by starting the simulation and clicking on the photoresistor (brown oval with squiggly line down the middle), then drag the brightness slider to adjust the simulated light input.

  2. In this lesson, you'll build this simulated circuit yourself along side the sample. To optionally build the physical circuit, gather up your Arduino Uno board, USB cable, solderless breadboard, an LED, resistors (220 ohm and 4.7k ohm), photoresistor, and breadboard wires.

  3. Continue to the next step.

Step 1: Build the Circuit

Take a look at the breadboard circuit in the workplane. It can be useful to look at a free-wired version of this sample circuit for comparison, pictured. In this step, you will build your own version of this circuit along side the sample in the workplane.

  1. Identify the photoresistor, LED, resistors, and wires connected to the Arduino in the Tinkercad Circuits workplane.
  2. Drag an Arduino Uno and breadboard from the components panel to the workplane, next to the existing circuit.
  3. Connect breadboard power (+) and ground (-) rails to Arduino 5V and ground (GND), respectively, by clicking to create wires.
  4. Extend power and ground rails to their respective buses on the opposite edge of the breadboard (optional for this circuit but good common practice).
  5. Plug the LED into two different breadboard rows so that the cathode (negative, shorter leg) connects to one leg of a resistor (anywhere from 100-1K ohms is fine).

    HINT:

    The resistor can go in either orientation because resistors aren't polarized, unlike LEDs, which must be connected in a certain way to function.

  6. Connect other resistor leg to ground.
  7. Wire up the LED anode (positive, longer leg) to Arduino pin 9.
  8. Drag a photoresistor from the components panel to your breadboard, so its legs plug into two different rows.
  9. Click to create a wire connecting one photoresistor leg to power.
  10. Connect the the other leg to Arduino analog pin A0.
  11. Drag a resistor from the components panel to connect the photoresistor leg connected to A0 with ground, and adjust its value to 4.7k ohms.
  12. Continue to the next step.

Step 2: Code With Blocks

Let's use the code blocks editor to listen to the state of the photoresistor, then set an LED to a relative brightness based on how much light the sensor sees. You may wish to refresh your memory of LED analog output in the Fading LED lesson.

  1. Click the "Code" button to open the code editor. The grey Notation blocks are comments for making note of what you intend for your code to do, but this text isn't executed as part of the program.
  2. Click on the Variables category in the code editor.
  3. To store the resistance value of the photoresistor, create a variable named "sensorValue".
  4. Drag out a "set" block.
  5. We'll store the state of our photoresistor in the variable sensorValue.
  6. Click on the Input category and drag out an "analog read pin" block, and place it into the "set" block after the word "to"
  7. Since our potentiometer is connected to the Arduino on pin A0, change the dropdown to A0.
  8. Click the Output category and drag out a "print to serial monitor" block.
  9. Navigate to the Variables category and drag your variable sensorValue onto the "print to serial monitor" block, and make sure the dropdown is set to print with a new line. Optionally start the simulation and open the serial monitor to verify readings are coming in and changing when you adjust the sensor. Analog input values range from 0-1023.
  10. Since we want to write to the LED with a number between 0 (off) and 255 (full brightness), we'll use the "map" block to do some cross-multiplication for us. Navigate to the Math category and drag out a "map" block.
  11. In the first slot, drag in a sensorValue variable block, then set the range from 0 to 255.
  12. Back in the Output category, drag out an analog "set pin" block, which by default says "set pin 3 to 0." Adjust it to set pin 9.
  13. Drag the map block you made earlier into the "set pin" block's "to" field to write the adjusted number to the LED pin using PWM.
  14. Click the Control category and drag out a wait block, and adjust it to delay the program for .1 seconds.
  15. Continue to the next step.

Step 3: Photoresistor Arduino Code Explained

When the code editor is open, you can click the dropdown menu on the left and select "Blocks + Text" to reveal the Arduino code generated by the code blocks. Follow along as we explore the code in more detail.

  1. int sensorValue = 0;
    

    Before the setup(), we create a variable to store the current value read from the potentiometer. It’s called int because it’s an integer, or any whole number.

    void setup()
    {
      pinMode(A0, INPUT);
      pinMode(9, OUTPUT);
      Serial.begin(9600);
    }
    

    Inside the setup, pins are configured using the pinMode() function. Pin A0 is configured as an input, so we can "listen" to the electrical state of the potentiometer. Pin 9 is configured as an output to control the LED. To be able to send messages, the Arduino opens a new serial communication channel with Serial.begin(), which takes a baud rate argument (what speed to communicate), in this case 9600 bits per second.

  2. void loop()
    {
      // read the value from the sensor
      sensorValue = analogRead(A0);
      // print the sensor reading so you know its range
      Serial.println(sensorValue);
    
    

    Anything after a set of slashes // is a comment, which helps folks understand in plain language what the program is intended to do, but is not included in the program your Arduino runs. In the main loop, a function called analogRead(); checks the state of pin A0 (which will be a whole number from 0-1023), and stores that value in the variable sensorValue.

  3.   // map the sensor reading to a range for the LED
      analogWrite(9, map(sensorValue, 0, 1023, 0, 255));
      delay(100); // Wait for 100 millisecond(s)
    }
    

    The line following the next comment is doing a lot at once. Remember analogWrite() takes two arguments, the pin number (9 in our case), and the value to write, which should be between 0 and 255. The inline function map() takes five arguments: the number to evaluate (the ever-changing sensor variable), the expected minimum and expected maximum, and the desired min and max. So the map() function in our case is evaluating the incoming sensorValue, and doing some cross multiplication to scale the output down from 0-1023 to 0-255. The result is returned into the second argument of analogWrite();, setting the brightness of the LED connected to pin 9.

  4. Continue to the next step.

Step 4: Build a Physical Arduino Circuit (optional)

To program your physical Arduino Uno, you'll need to install the free software (or plugin for the web editor), then open it up. Various photocells have different values, so if your physical circuit is not working, you may need to change the resistor that is paired with it. Learn more about voltage dividers in the Instructables Electronics Class lesson on resistors.

  1. Wire up the Arduino Uno circuit by plugging in components and wires to match the connections shown here in Tinkercad Circuits. For a more in-depth walk-through on working with your physical Arduino Uno board, check out the free Instructables Arduino class.
  2. Copy the code from the Tinkercad Circuits code window and paste it into an empty sketch in your Arduino software, or click the download button (downward facing arrow) and open the resulting file using Arduino.You can also find this example in the Arduino software by navigating to File -> Examples -> 03.Analog -> AnalogInOutSerial.
  3. Plug in your USB cable and select your board and port in the software’s Tools menu.
  4. Upload the code and use your hand to cover the sensor from receiving light, and/or shine a light on your sensor!
  5. Open the serial monitor to observe your sensor values. It's likely that real world values will not extend all the way to 0 or all the way to 1023, depending on your lighting conditions. Feel free to adjust the 0-1023 range to your observed minimum and observed maximum in order to get the maximum brightness expression range on the LED.
  6. Continue to the next step.

Step 5: Next, Try...

Now that you’ve learned to read a photoresistor and map its output to control the brightness of an LED, you're ready to apply those and other skills you've learned so far.

  1. Can you swap out the LED for another type of output, like a servo motor, and create some code to reflect the sensor's current light level as a certain position along a gauge?
  2. Try swapping out your photoresistor for other analog inputs such as an ultrasonic distance sensor or potentiometer.
  3. Learn more about how to monitor your Arduino's digital and analog inputs through the computer using the Serial Monitor.