Using the Circuit Playground Express (CPX) Library

The value of the light sensor is available as cpx.light. You can use this, for example, to plot light levels over time or trigger an alarm if the value gets high (like when an intruder turns on the lights).

The example below uses the plot capability of the Mu editor to plot light readings. The time.sleep function waits a tenth of a second between values.

# SPDX-FileCopyrightText: 2017 Kattni Rembor for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import time
from adafruit_circuitplayground.express import cpx

while True:
    print((cpx.light, ))
    time.sleep(0.1)

When you run this program with the Mu editor, open the REPL via the Serial button to see it print out values for the light. The numbers will get higher with bright light (about 7500 next to white on a monitor), and go lower you put a finger on the sensor (below a thousand covering the board with your hands).

In the code above, the numbers are printed as Python tuples, grouped fixed values, so the values are printed in parenthesis with a comma. Why print a tuple verses just the number? 

Click the Mu Plotter button. The plotter pulls out next to the REPL/Serial window and you get a graph of the light value over time. Go ahead and try covering the sensor and putting it up to light to see the changes.

The light values from the CPX library and the lower level analog read library are scaled differently.

Using Lower-Level Library Calls With the Light Sensor

To read the light sensor, you will need three libraries:

  • analogio - to access the analog values from the sensor
  • board - to use the pin name of the light sensor
  • time - to read values in specific intervals

The analogio function AnalogIn takes the board's light sensor pin and creates an object that will return the value of the sensor when we need it.

In the simple example, the light sensor value is read forever (in a while True: loop) and it prints out the sensor's value every tenth of a second (10 times a second).

You need some time between sensor readings. If you remove the time.sleep call entirely, the board may lock up trying it's hardest to pump out values.
# SPDX-FileCopyrightText: 2018 Anne Barela for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import time
import analogio
import board

# Create the light sensor object to read from
light = analogio.AnalogIn(board.LIGHT)

# Do readings, be sure to pause between readings
while True:
    print((light.value, ))
    time.sleep(0.1)

This guide was first published on Jul 26, 2018. It was last updated on Jul 26, 2018.

This page (CircuitPython) was last updated on Mar 06, 2023.

Text editor powered by tinymce.