This exercise uses the light sensor on the board. The position of the light sensor is shown in the image below (an eye symbol marks its position on the board).
❗Before continuing, open the REPL window in mu-editor to see any printed output. Opening this window is done by clicking Serial
on the menu bar. This will bring up an additional window at the bottom (see image).
Run the following code on the board by copying it to the code.py
file and saving the file.
import board
import time
import analogio
light_sensor = analogio.AnalogIn(board.LIGHT)
while True:
current_light = light_sensor.value
print(current_light)
time.sleep(1)
This code creates a variable light_sensor
that allows getting the current value of the sensor using the line current_light = light_sensor.value
. Therefore, this code gets the value of the light sensor and stores it in the variable current_light
. Next, the value is printed, and the program waits 1 second before repeating the process. Below is an example of the output you can expect:
While the program is running, place your finger over the light sensor. Or place your hand over the complete board. You should see the value printed change. Lower values correspond to less light detected by the sensor. You can also shine a light (your phone’s flash) on the sensor. The value should increase.
For the challenges below, start with the following code.
import time
import time
import board
import neopixel
import analogio
light = analogio.AnalogIn(board.LIGHT)
leds = neopixel.NeoPixel(board.NEOPIXEL, 10)
threshold = 2500
while True:
current_light = light.value
print(current_light)
time.sleep(1)
The code initializes the light sensor and the NeoPixel LEDs on the board. It then sets a threshold value of 2500. Inside the while loop, the current value of the light sensor is read and stored in the variable current_light
. The value is printed to the REPL window. The code then pauses for 1 second before repeating the process. This allows you to continuously monitor and observe the values from the light sensor.
Edit the code above such that one of the board’s LEDs comes on if the value of current_light
is larger than threshold
. If the value of current_light
is smaller than threshold
, the LED goes off. The aim is for you to be able to switch on and off the LED by placing your finger over the light sensor. For this to work, you might have to change the value of threshold
. Please try this for yourself before looking at the solution.
Tip: do not use LED 0, as switching on this LED will interfere with measuring the light value.