We're going to use CircuitPython, Mu, and the light sensor on Circuit Playground Express to plot light levels. We have a simple nine-line piece of code below. We'll run this code on our Circuit Playground Express and use Mu to plot the sensor data that CircuitPython prints out.

Save the following as code.py on your Circuit Playground Express board, using the Mu editor:

# SPDX-FileCopyrightText: 2018 Phillip Torrone for Adafruit Industries
# SPDX-License-Identifier: MIT

import time

import analogio
import board

light = analogio.AnalogIn(board.LIGHT)

while True:

On the first few lines we import analogio, board and time, and setup our light sensor. Inside our while loop, we are print()-ing the light level. The time.sleep() is to keep from spamming the results - if they're too fast, they get difficult to read!

Note that the Mu plotter looks for tuple values to print. Tuples in Python come in parentheses () with comma separators. If you have two values, a tuple would look like (1.0, 3.14) Since we have only one value, we need to have it print out like (1.0,) note the parentheses around the number, and the comma after the number. Thus the extra parentheses and comma in print((light.value,)).

Once you have everything setup and running, try placing your hand over the Circuit Playground Express, and watch the plotter immediately react! When you block the light from reaching the CPX, the graphing plotter line goes down. If you shine a flashlight on it to add more light, the plotter goes up!

It's a really easy way to test out your sensors and get a feeling for analog reads in CircuitPython!

Note you can have the text REPL on the left and resize the plotter to be big and on the right like above. That way you see the numbers and the graph at the same time. The plotter will automatically re-scale depending on light levels.

This guide was first published on Apr 09, 2018. It was last updated on Jun 14, 2024.

This page (Light) was last updated on Jun 14, 2024.

Text editor powered by tinymce.