The compass and temperature on the micro:bit

Lesson 8 of 17 · MicroPython and the micro:bit

Besides the LED matrix and the buttons, the micro:bit has built-in sensors that let it "feel" its surroundings. In this lesson we meet two important sensors: the compass and the temperature sensor.


These sensors are often used in games, navigation and smart devices, and in MicroPython they are very easy to use.


The temperature sensor


The micro:bit can measure the temperature around it (in degrees Celsius). In MicroPython we use the function temperature().



from microbit import *

while True:
    t = temperature()
    display.scroll(str(t) + "C")
    sleep(2000)

This program:

  • reads the current temperature
  • turns the number into text
  • shows it on the LED matrix
  • waits 2 seconds and repeats the process

✔ The temperature changes if you touch the micro:bit with your fingers, because the sensor warms up.


The compass (direction towards north)


The micro:bit has a built-in digital compass that can tell which direction the device is facing. The value is measured in degrees (0–360°).


Before it is used for the first time, the compass must be calibrated. MicroPython does this automatically when you call a compass function.


How the compass on the micro:bit works

The compass uses a magnetometer that detects the Earth's magnetic field. From that the micro:bit can work out the direction in degrees from 0 to 360.


from microbit import *
compass.calibrate() # calibrating the compass
while True:
    heading = compass.heading()
    display.scroll(str(heading))
    sleep(1000)

The values mean:

  • 0° — north
  • 90° — east
  • 180° — south
  • 270° — west

Example: Find north


In this example the micro:bit shows an arrow when it is facing north.



from microbit import *

while True:
    heading = compass.heading()

    if heading < 10 or heading > 350:
        display.show(Image.ARROW_N)
    else:
        display.clear()

    sleep(300)

In this way you can see how sensors are combined with:

  • conditions (if)
  • loops
  • graphics on the LED matrix

Comparison with MakeCode


If you worked in MakeCode before, this is the same as the blocks:

  • temperature (°C)
  • compass heading (°)

The difference is that now:

  • you can clearly see the flow of the program
  • you learn real Python syntax
  • it is easier to move on to more complex projects

✔ You can see more about the blocks on the official MakeCode micro:bit page:
https://makecode.microbit.org



More advanced work with temperature


Example 1 — A digital thermometer with an indicator


from microbit import *

while True:
    t = temperature()

    if t < 18:
        display.show(Image.SAD)
    elif 18 <= t <= 25:
        display.show(Image.HAPPY)
    else:
        display.show(Image.ANGRY)

    sleep(1000)

The micro:bit shows a different icon depending on the temperature.


Example 2 — Button B shows the temperature


from microbit import *

while True:
    if button_b.was_pressed():
        t = temperature()
        display.scroll(str(t) + "C")

The temperature is shown only when you press the button.


Mini project — A smart thermometer


Let us make a device that:

  • measures the temperature
  • remembers the highest measured value
  • button A shows the current temperature
  • button B shows the maximum temperature


from microbit import *

max_temp = temperature()

while True:
    t = temperature()

    if t > max_temp:
        max_temp = t

    if button_a.was_pressed():
        display.scroll("T:" + str(t))

    if button_b.was_pressed():
        display.scroll("MAX:" + str(max_temp))

    sleep(500)

Example — Showing the direction with an arrow



from microbit import *

while True:
    heading = compass.heading()

    if heading < 45 or heading > 315:
        display.show(Image.ARROW_N)
    elif 45 <= heading < 135:
        display.show(Image.ARROW_E)
    elif 135 <= heading < 225:
        display.show(Image.ARROW_S)
    else:
        display.show(Image.ARROW_W)

    sleep(300)

Now the micro:bit points to one of the four main directions.


Mini project — Find north


Task: Turn the micro:bit towards north. If it is pointing exactly, ✓ is shown.


from microbit import *

while True:
    heading = compass.heading()

    if heading < 10 or heading > 350:
        display.show(Image.YES)
    else:
        display.show(Image.NO)

    sleep(200)

How does the compass measure direction?

           0° (North)
                ↑
 270° (West) ←   → 90° (East)
                ↓
           180° (South)

The compass gives a number between 0 and 360. We divide that number into intervals.


Mini project — An expedition device


A device where:

  • Button A — shows the temperature
  • Button B — shows the direction
  • If the temperature is above 30°C → a warning


from microbit import *

while True:
    if button_a.was_pressed():
        t = temperature()
        display.scroll(str(t) + "C")

        if t > 30:
            display.show(Image.SKULL)
            sleep(1000)

    if button_b.was_pressed():
        heading = compass.heading()
        display.scroll(str(heading))

    sleep(200)

Mini project — A digital compass

In this mini project we make a digital compass that shows the main points of the compass: N, E, S, W.

The micro:bit uses the magnetometer to detect the direction in degrees from 0 to 360. From that value we can work out where north, east, south and west are.

Before using the compass you need to calibrate it. The micro:bit will ask you to move it around in a circle.


from microbit import *

# calibrating the compass
compass.calibrate()

while True:

    heading = compass.heading()

    if heading < 45 or heading > 315:
        display.show("N")

    elif heading < 135:
        display.show("E")

    elif heading < 225:
        display.show("S")

    else:
        display.show("W")

    sleep(500)

How the program works

  • compass.calibrate() calibrates the compass
  • compass.heading() returns the direction from 0 to 360 degrees
  • the conditions decide the point of the compass
  • display.show() shows a letter on the LED matrix

Test the program

  • Turn the micro:bit around
  • Watch how the letter changes
  • Compare it with a real compass or a phone

Challenge (advanced task)

Try to show the diagonal directions as well:

  • NE — north-east
  • NW — north-west
  • SE — south-east
  • SW — south-west

This project is the basis for:

  • navigation devices
  • orientation games
  • robot projects

Tasks for independent work


Task 1

Make a program that shows:

  • an LED dot that lights up if the temperature is below 15°C

Task 2

Show an arrow only when the device is facing east.

Task 3

Make a combined device:

  • If the temperature is higher than 28°C and the device is facing south → show "HOT"

Task 4 (challenge)

Keep the minimum and the maximum temperature during the lesson.


Mini project — A small weather station


Let us make a small weather station that:

  • measures the temperature
  • shows the direction (compass)
  • remembers the minimum and the maximum temperature
  • button A — the current temperature
  • button B — the direction of movement
  • buttons A+B — the MIN and MAX temperature

The program


from microbit import *

# Starting values
current = temperature()
min_temp = current
max_temp = current

while True:

    current = temperature()

    # Updating the minimum and the maximum temperature
    if current < min_temp:
        min_temp = current

    if current > max_temp:
        max_temp = current

    # Button A - the current temperature
    if button_a.was_pressed():
        display.scroll("T:" + str(current) + "C")

    # Button B - the direction (compass)
    if button_b.was_pressed():
        heading = compass.heading()
        display.scroll(str(heading) + "deg")

    # Buttons A+B - min and max
    if button_a.is_pressed() and button_b.is_pressed():
        display.scroll("MIN:" + str(min_temp))
        display.scroll("MAX:" + str(max_temp))

    sleep(300)

How does the project work?

  • The program keeps measuring the temperature
  • It remembers the lowest and the highest value
  • The compass gives the orientation in degrees
  • The buttons choose what we want to see

A visual explanation (the flow of the program)

          START
             ↓
     read the temperature
             ↓
   update MIN and MAX
             ↓
  is a button pressed?
        ↓        ↓
        A        B
      show       show
      temp.      direction

Extended version — Warnings

Add warnings for extreme temperatures:


    if current > 30:
        display.show(Image.SKULL)
        sleep(1000)

    if current < 5:
        display.show(Image.SAD)
        sleep(1000)

An experiment for the lesson

  • Touch the micro:bit with your fingers and watch the MAX temperature
  • Take it next to a window (a colder place)
  • Compare the results between groups of students

Tasks for independent work

Task 1

Show the north arrow when button B is pressed, instead of the numerical value.

Task 2

Add a "reset of the weather station" when the micro:bit is shaken.

Task 3 (challenge)

If the temperature is above 28°C and the device is facing south — show the message "WARM IN THE SOUTH".


Educational goals

  • Combining several sensors
  • Working with minimum/maximum logic
  • Compound conditions (AND)
  • Project thinking
  • Connecting with geography and physics

Mini project — A digital navigator


In this project the micro:bit becomes a small navigator. The device:

  • shows the direction (compass)
  • reacts to tilt (accelerometer)
  • helps you find a given direction

The idea of the project

We set a target — for example EAST (90°). The micro:bit shows:

  • ✓ if you are facing the target
  • an arrow left/right if you need to turn
  • tilting forwards/backwards changes the mode

The basic version


from microbit import *

TARGET = 90   # East

while True:
    heading = compass.heading()

    # the difference from -180 to 180 (e.g. 350° and 0° differ by -10°, not by 350°)
    difference = (heading - TARGET + 180) % 360 - 180

    if abs(difference) < 10:
        display.show(Image.YES)

    elif difference > 0:
        display.show(Image.ARROW_W)  # turn left

    else:
        display.show(Image.ARROW_E)  # turn right

    sleep(200)

How does this work?

  • The compass gives an angle of 0–360°
  • We calculate the difference from the target angle
  • If the difference is small → we have arrived
  • If it is not → we show the direction of the correction

Extended version — Tilt changes the target

If you tilt the micro:bit:

  • to the left → the target is WEST (270°)
  • to the right → the target is EAST (90°)
  • held flat → the target is NORTH (0°)

from microbit import *

TARGET = 0

while True:

    # Changing the target by tilting
    x = accelerometer.get_x()

    if x > 300:
        TARGET = 90
    elif x < -300:
        TARGET = 270
    else:
        TARGET = 0

    heading = compass.heading()
    difference = (heading - TARGET + 180) % 360 - 180   # from -180 to 180

    if abs(difference) < 10:
        display.show(Image.YES)
    elif difference > 0:
        display.show(Image.ARROW_W)
    else:
        display.show(Image.ARROW_E)

    sleep(200)

A visual explanation

       0° (North)
           ↑
 270° ←        → 90°
           ↓
        180°

Tilt chooses the target.
The compass checks whether you are facing that target.

Mini challenge — Explorer mode

Add button A:

  • Button A chooses a random direction
  • The student has to find it

from microbit import *
import random

TARGET = 0

while True:

    if button_a.was_pressed():
        TARGET = random.randint(0, 359)

    heading = compass.heading()
    difference = (heading - TARGET + 180) % 360 - 180   # from -180 to 180

    if abs(difference) < 10:
        display.show(Image.HAPPY)
    else:
        display.show(Image.ARROW_E)

    sleep(200)

Tasks for independent work

Task 1

Instead of only left/right, also add up/down arrows for north and south.

Task 2

Add a sound signal (if you use a micro:bit V2) when the target is found.

Task 3 (advanced)

Use a tolerance of 5° instead of 10°. Is it harder to hit the target?


What do the students learn?

  • Working with angles (0–360°)
  • Calculating the difference between values
  • Combining two sensors
  • Project thinking
  • The link between mathematics and programming

Mini project — The "Treasure hunt" game


The micro:bit chooses a random direction (the secret location of the treasure). Your task is to turn around until you find the exact direction.

  • Button A — starts a new game
  • The compass guides the player
  • When the direction is hit — a reward appears

How does the game work?

  • The micro:bit chooses a random angle (0–359°)
  • The player turns around
  • If they are close to the target (±10°) — they have found the treasure

The program


from microbit import *
import random

TARGET = None
TOLERANCE = 10

while True:

    # Starting a new game
    if button_a.was_pressed():
        TARGET = random.randint(0, 359)
        display.scroll("GO!")

    if TARGET is not None:
        heading = compass.heading()
        difference = abs(heading - TARGET)

        # Correction for passing over 0°
        if difference > 180:
            difference = 360 - difference

        if difference <= TOLERANCE:
            display.show(Image.DIAMOND)
        else:
            display.show(Image.ARROW_E)

    sleep(200)

An important explanation — Why do we use 360 - difference?

If the target is 350° and the compass shows 10°, the difference is not 340° — it is only 20°.

350°   ...   0°   ...   10°
      ← 20° →

That is why we calculate around the circle.


Extended version — Hot / cold

Instead of one arrow, the game can show how close you are:

  • Image.DIAMOND — you have found the treasure (up to 10°)
  • Image.HAPPY — you are close (up to 30°)
  • Image.ASLEEP — medium distance (up to 60°)
  • Image.SAD — far away

if difference <= 10:
    display.show(Image.DIAMOND)
elif difference <= 30:
    display.show(Image.HAPPY)
elif difference <= 60:
    display.show(Image.ASLEEP)
else:
    display.show(Image.SAD)

Advanced version — Add tilt

Tilting the device can be used for:

  • Changing the difficulty of the game
  • Setting the tolerance

Example:


x = accelerometer.get_x()

if x > 300:
    TOLERANCE = 5     # harder
elif x < -300:
    TOLERANCE = 20    # easier
else:
    TOLERANCE = 10

Organising the lesson (activity)

  • The students work in pairs
  • One holds the device and looks for the treasure
  • The other writes down the number of attempts
  • The winner is the one who finds the direction fastest

Tasks for independent work


Task 1

Add a counter of attempts.

Task 2

Add a countdown timer (30 seconds).

Task 3 (advanced)

If the player does not find the treasure in 30 seconds — the game resets.


What do the students learn?

  • Calculating around a circle (360°)
  • The difference between angles
  • Working with random values
  • Combining the compass and the accelerometer
  • Developing algorithmic thinking

Hidden mini quiz — The compass and temperature

Check whether you understand how the compass and the temperature sensor work in MicroPython.

Open the quiz

Mini quiz: The compass and temperature

1. Which function returns the direction of the compass?




2. What range of values does the compass return?




3. Which function measures the temperature?




4. What does a compass value of 0° mean?




5. Why does the compass need to be calibrated?







Mini project — An automatic light

This mini project connects a light sensor with an LED or another actuator. The idea: when the light around is weak, the device switches a light on; when there is enough light, the light is switched off.


from microbit import *

while True:
    light = pin0.read_analog()  # reading from the light sensor

    if light < 300:              # if the light is below the threshold
        pin1.write_digital(1)    # switch the light on
    else:
        pin1.write_digital(0)    # switch the light off

    sleep(200)                   # a short pause

What you learn with this project:

  • Reading analog sensors (read_analog())
  • Controlling a digital output (write_digital())
  • Using conditional statements (if) in a real project
  • A loop that runs all the time (while True)

Ideas for going further

You can add:

  • More sensors to detect light and movement at the same time
  • A servo motor that moves when the sensor detects a dark place
  • A mini quiz or exercise to check your understanding of analog and digital signals

Related: the same topic in MakeCode and other lessons

If you worked with the micro:bit in blocks in the 5th or 6th grade, compare the blocks with the MicroPython code: