Lesson goal: Read the light level and plot it in real time

Previous: Real time temperature plot (nicer) | Home | Next: Linearly scale a potentiometer

As seen in a previous lesson, we were able to read a temperature and plot it in real-time, on a nice-looking chart. In this lesson, let's do the same, but for the ambient light level.

As you run this lesson, try to change the light level around your circuit (cover the sensor with your handle, turn the room-lights on and off, etc. See the notes below for a science-project-type lesson.

Now you try. Wire up the circuit and run the code given. See if the numbers change as you change the light level around your circuit.

Type your code here:


See your results here:

For this lesson, you'll need this circuit

Run the code above. You should see a bunch of numbers scrolling by. The numbers should get smaller when it gets darker, and larger when it gets lighter. If this works, then do this:

  1. Add the line new_chart('Time (seconds)','Temperature','line') at the very beginning of the code to start a new chart.

  2. Replace the println(...) line with graph_point(t,volts) to plot the light level in volts as time goes on in variable t.
Now, as you change the light level, you should see the graph respond accordingly.

Science Project

Here's some code that will take a light reading once per minute for 24 hours (1,440 minutes). If you can, set your light sensor/circuit near a window, and let it run for a whole day. You can electronically capture sunrise and sunset! What do you think the graph will look like?

new_chart('Time (seconds)','Light level','line')
i = 0
start = seconds()
while i < 1440 do
 t = seconds()
 if t - start > 60 then
  t = seconds()
  volts = analogread(A0)
  graph_point(t,volts)
  i = i + 1
  start = t
 end
end
Note! When you run this code, nothing will appear to happen! But wait a minute and you'll see the first light level point plotted. Then another minute, etc. Dismiss.
Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.