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 power of the sensor 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/

Step 1 - Importing Libraries

from microbit import *

To use the features of the micro:bit with MicroPython we need to import the microbit library. Using * means we can import the library and use the contents without starting every command with microbit.

Step 2 - Time Travel

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.

Step 3 - Looping Forever

while True:

To keep our code running while the micro:bit is powered up, a while True loop is used. This works in the same way as the forever block used in Makecode.

Step 4 - Temperature Check

	if temperature() > 20:

Using a conditional test, we check to see if the temperature is greater than 20C. The value of 20 will need to be tweaked based on the temperature of your home.

Step 5 - Showing an image

		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.

Step 6 - Pause for thought

		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.

Step 7 - But what happens when it is cold?

	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

Step 8 - If it is cold, then I am sad

		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.

Step 9 - Another short pause

		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.

Full Code Listing:

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)