In this activity you will begin to explore how to use logic, and in particular IF statements to create a night light. You will be asking the question, “is it too dark”. You will then be creating various outputs to cater for the different answers to that question. For example, if the answer is yes then you will need to create an output that lights up the LED matrix on the micro:bit.
- To understand how the micro:bit’s on board light level sensor works and use it as an input.
- Use IF statements to ask a question.
- Create multiple outputs to be assigned to the different outcomes to the question.
Download the Code
Click the button below to download the MakeCode editor code for this lesson. The hex file is contained in a zip folder.
Kindly refer to our download the code page for instructions on how to upload your code onto the micro:bit. Please use instructions set A.
This code can also be uploaded into the MakeCode editor.
Time to Code
As you go through these steps please note that there is an image of the completed code to the right.
- Begin by selecting the ‘forever’ block from the ‘basic’ tab.
- Open the ‘logic’ tab and select the ‘if else’ block. Insert this block into the ‘forever’ block.
- Next you need to create the if statement which will ask our question. Again open the ‘logic’ tab and select the ‘less than’ block. Insert this into the if statement. We to state that if the light level is less than a certain amount do something.
- Find the ‘light level’ block in the ‘input’ tab and insert it into the statement. The light level sensor gives a value from 0 – 255 with 0 being pitch black. Set the threshold to 100.
- Next select the ‘show leds’ block form the ‘basic’ tab and insert it into the if statement. This is your first output.
- Finally select the ‘clear screen’ block from the ‘basic’ tab and insert it into the else statement. This is your second output.
- The code is now finished! Download your code and upload it onto the micro:bit. The instructions for this can be found on the download the code page. Please use instructions set B.
If the light level on the sensor drops below a threshold of 100 then the entire LED matrix will light up. Once the light level increases again to above 100 then the LED matrix will turn off.
Taking it Further
- Create a smart night light the automatically adjusts its own brightness dependingon the light level reading from the sensor.
- Connect some external LEDs and create a mood lamp.
Keep in Touch
We would love to keep in touch with you and as a result aid you along your digital making journey.
Becoming a digital maker subscriber means you will receive exclusive offers and we will keep you up to date with new resources and kits, as well as upcoming events and workshops.
Let us know how your digital education journey is progressing. Send us pictures and videos of your awesome creations and use the hashtag below.