In this activity, you'll create a program that turns your micro:bit into an automatic night light.
The LEDs will brighten as the surrounding environment gets darker.
BBC micro:bit
New project at https://python.microbit.org/v/3
Create a program that:
Reads the current light level from the micro:bit
Adjusts the brightness of all LEDs based on the light level
Updates the display continuously
Here's the basic structure for your program:
from microbit import *
while True:
# Get the current light level
light_level = display.read_light_level()
# Your code here:
# 1. Print the light level to the console
# 2. Map and clamp the light level to LED brightness
# 3. Set all pixels to the calculated brightness
# Add a delay to prevent too rapid updates
sleep(100)
First, let's see what kind of values we get from the light sensor:
from microbit import *
while True:
light_level = display.read_light_level()
print(light_level)
sleep(100)
Run this code and observe the values in the console. Try covering the micro:bit or shining a light on it. What's the range of values you see?
Now that you know the range of light levels, you need to map these to LED brightness levels (0-9).
Refer to the mapping formula from the previous lesson if necessary, however you should find this one a bit easier.
You'll need to adjust this formula to reverse the relationship (darker environment = brighter LEDs).
After mapping, make sure to clamp the values between 0 and 9.
To set all LEDs to the same brightness, you can use nested loops.
Then, use display.set_pixel(x, y, brightness)
Once your basic night light is working, try these challenges:
Make the night light turn on only below a certain light level
Use A and B buttons to adjust the sensitivity of the night light
Write functions for 'mapping' and 'clamping' that you can reuse in future projects