By the end of this lesson, students will be able to:
compass.calibrate().The Micro:bit has a built-in magnetometer (compass sensor) that can measure the Earth’s magnetic field and give you a heading from 0° to 359°, where:
But the compass is not accurate until you calibrate it using:
compass.calibrate()
During calibration, students will tilt the Micro:bit and draw a pattern on the LED display. After calibration, the compass will return more accurate heading values.
Program Name: P1_lastname_compassDirection.py
Device: Micro:bit v2
Language: Python (MicroPython)
compass.calibrate() once.compass.heading().START
IMPORT microbit library and compass
CALL compass.calibrate() // user tilts Micro:bit to complete calibration
REPEAT FOREVER:
GET current_heading from compass.heading() // result is 0 to 359
IF heading < 45 OR heading >= 315:
direction = "N"
ELSE IF heading < 135:
direction = "E"
ELSE IF heading < 225:
direction = "S"
ELSE:
direction = "W"
DISPLAY direction letter on the LED screen
WAIT 0.2 seconds
END REPEAT
END
Students can copy this into the Micro:bit Python editor (or Mu) and download it to their boards.
from microbit import *
import compass
# Step 1: Calibrate the compass once at the start
compass.calibrate()
while True:
# Step 2: Read the current heading (0 - 359 degrees)
heading = compass.heading()
************ more is needed ***********
# Step 4: Small delay so the display does not flicker too fast
sleep(200)
P1_lastname_compassDirection.py.compass.calibrate() and compass.heading())..hex file to the Micro:bit.If you want to push your stronger students:
"NE" using display.scroll("NE").Image.ARROW_N, Image.ARROW_E, etc. (or custom arrow images) instead of letters.display.scroll(str(heading)) to show the actual degree value occasionally.?, and the player must rotate until they face that direction.Have students answer in 2–3 sentences each:
The name of the file will be:
PX_lastname_Directions
PX_lastname_Directions.png — Screenshot inside Python editor showing your code.PX_lastname_Directions.py — Your Python source file.PX_lastname_Directions.txt — Plain-text copy of your code.PX_lastname_Directions.hex — Hex file to run on the physical micro:bit.PX_lastname_Directions.mp4 — Short demo video of the program running on the board.