Trybotics Logo

Light Sensor (Photoresistor) With Arduino in Tinkercad

DESCRIPTION

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 control LEDs with Arduino's analog output, and 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.

Explore the sample circuit embedded here in the workplane by clicking Start 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.

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.

You can follow along virtually using Tinkercad Circuits. You can even view this lesson from within Tinkercad (free login required)! Explore the sample circuit and build your own right next to it. Tinkercad Circuits is a free browser-based program that lets you build and simulate circuits. It's perfect for learning, teaching, and prototyping.

Description:

Take a look at the breadboard circuit pictured. 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.

To follow along, load up a new Tinkercad Circuits window and build your own version of this circuit along side the sample.

Identify the photoresistor, LED, resistors, and wires connected to the Arduino in the Tinkercad Circuits workplane.

Drag an Arduino Uno and breadboard from the components panel to the workplane, next to the existing circuit.

Connect breadboard power (+) and ground (-) rails to Arduino 5V and ground (GND), respectively, by clicking to create wires.

Extend power and ground rails to their respective buses on the opposite edge of the breadboard (optional for this circuit but good common practice).

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). The resistor can go in either orientation because resistors aren't polarized, unlike LEDs, which must be connected in a certain way to function.

Connect other resistor leg to ground.

Wire up the LED anode (positive, longer leg) to Arduino pin 9.

Drag a photoresistor from the components panel to your breadboard, so its legs plug into two different rows.

Click to create a wire connecting one photoresistor leg to power.

Connect the the other leg to Arduino analog pin A0.

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.

Description:

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.

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.

Click on the Variables category in the code editor.

To store the resistance value of the photoresistor, create a variable named "sensorValue".

Drag out a "set" block. We'll store the state of our photoresistor in the variable sensorValue.

Click on the Input category and drag out an "analog read pin" block, and place it into the "set" block after the word "to"

Since our potentiometer is connected to the Arduino on pin A0, change the dropdown to A0.

Click the Output category and drag out a "print to serial monitor" block.

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.

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.

In the first slot, drag in a sensorValue variable block, then set the range from 0 to 255.

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.

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.

Click the Control category and drag out a wait block, and adjust it to delay the program for .1 seconds.

Description:

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.

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.

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.

  // 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.

Description:

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.

    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.

    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.

    Plug in your USB cable and select your board and port in the software’s Tools menu.

    Upload the code and use your hand to cover the sensor from receiving light, and/or shine a light on your sensor!

    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.

    Description:

    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.

    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?

    Try swapping out your photoresistor for other analog inputs such as an ultrasonic distance sensor or potentiometer.

    Learn more about how to monitor your Arduino's digital and analog inputs through the computer using the Serial Monitor.


    YOU MIGHT ALSO LIKE