About the Author
Les is a maker and trainer who has worked with the Raspberry Pi Foundation and the BBC to deliver computing training.
Did you know that the micro:bit has a built-in temperature sensor? It is part of the processor and using MicroPython we can unlock the sensor's power and use it as an input in a project.
In this project we will show a smiley face when it is warm, but a sad face when it gets too cold.
For this project, we shall be using MicroPython via the Mu editor.
To install Mu please follow the instructions on the Mu website https://codewith.mu/
from microbit import *
To use the features of the micro:bit with MicroPython we need to import the microbit library. Using * means importing the library and using the contents without starting every command with microbit.
import utime
To control the speed at which our code will run we need to import the utime library. This library has a function which can pause the running code.
while True:
A while True loop is used to keep our code running while the micro:bit is powered up. This works in the same way as the forever block used in Makecode.
if temperature() > 20:
Using a conditional test, we check whether the temperature is greater than 20C. The value of 20 will need to be tweaked based on the temperature of your home.
display.show(Image.HAPPY)
To show an image on the micro:bit’s LED matrix we use the display.show() function and to show a happy face if the temperature is greater than 20C.
utime.sleep(1)
Using the sleep function from the utime library we instruct the micro:bit to wait for one second. This will show the smiling face image for one second.
else:
If the temperature is not greater than 20C, we need to do something else, and to do that we use an else condition to catch any other scenario.
display.show(Image.SAD)
When the micro:bit is cold, we will show an unhappy face using the display.show() function. This can be changed to whatever you wish.
utime.sleep(1)
When the micro:bit is cold, we will show an unhappy face using the display.show() function. This can be changed to whatever you wish. To ensure that we can see the sad image on the micro:bit we need to add a short pause. This will be the last line of code for the project, and now save the code to your computer as temperature-control.py and then when ready click on Flash to send the code to the micro:bit. When finished, you should see an unhappy face. Touch the processor on the back of the micro:bit and the warmth of your finger will trigger the smiley face to appear.
from microbit import * import utime while True: if temperature() > 20: display.show(Image.HAPPY) utime.sleep(1) else: display.show(Image.SAD) utime.sleep(1)