Skip to content

Digital Compass

Level Beginner
Board V1 & V2
Parts micro:bit
Source 11 compass.py

What you'll build

A compass needle on the LED matrix that always points north. Press A to scroll the heading in degrees, or B to scroll the direction (N, NE, E...).

Code

11 compass.py
'''
Example: Digital compass with the built-in magnetometer in micro:bit
By: Meqdad Darwish
'''
from microbit import *

DIRECTIONS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

while True:
    # The first reading starts calibration: tilt the board until every LED is lit
    heading = compass.heading()  # 0-359 degrees, 0 = north

    if button_a.was_pressed():
        display.scroll(str(heading))
    elif button_b.was_pressed():
        display.scroll(DIRECTIONS[((heading + 22) // 45) % 8])
    else:
        # Pick the clock hand that points north
        needle = ((15 - heading) // 30) % 12
        display.show(Image.ALL_CLOCKS[needle])
        sleep(100)

Calibrating

The first time it runs, the micro:bit asks you to tilt it to fill the screen: roll it around until every LED is lit. Calibrate again with compass.calibrate() if the readings drift or you move near metal.

How it works

  • compass.heading() returns 0–359°, the direction the top of the board (the edge opposite the pins) faces. 0° is north, 90° is east.
  • Image.ALL_CLOCKS is a list of 12 clock-hand images, one every 30°. ((15 - heading) // 30) % 12 picks the hand pointing back towards north: turn to face east (90°) and the needle points left, to 9 o'clock.
  • (heading + 22) // 45 splits the circle into eight 45° slices, centred on N, NE, E and so on.

Keep the board flat: the heading is only accurate when the micro:bit is level.

Try this next

  • Show an arrow that points to a chosen direction, like your front door.
  • Use compass.get_field_strength() to make a metal detector.
  • Pair it with the Spirit Level so you know when the board is flat enough.