The light sensors on the board

The LEDs on the micro:bit board can be used to sense the amount of ambient light (i.e., they can be used as an input or a sensor). The challenges in this section use the light sensors on the board. More technical details about how the board senses the ambient light level can be found here:

MicroBitLightSensor - micro:bit runtime

Reading (and changing) the ambient light value

Run the following code on the simulator.

while True:
    value = input.light_level()

This code reads the current ambient light level and stores it in a variable value. This is done over and over again. When you run this, the simulator's interface shows a slider that can be used to change the ambient light level in the simulator (see the image below). Using the mouse, you can drag the vertical line in this indicator down or up to increase and decrease the amount of light in the simulator. The values run from 0 (no light) to 255 (maximum amount of light).

Untitled

Challenges

Now you understand how to read (and change) the ambient light. You are ready to try and complete the following challenges. For these challenges, start with the following code.

threshold = 100
while True:
    current_light = input.light_level()

Challenge 1

Edit the code above such that one of the micro:bit board’s LEDs (you can pick which) 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 changing the ambient light value using the slider.

Challenge 2

Edit the code above to obtain the following behavior. The number of LEDs changes depending on the amount of light detected. Select three light levels such that,

  1. If the light level is below 50, all LEDs are switched off
  2. For a low light level (>50), one LED turns on
  3. For a medium light level (>150), two LEDs turn on
  4. For a high light level (>200), three LEDs turn on