2.13. Magnetometer#
The magnetometer (compass) senses the orientation of the board relative to the Earth’s magnetic field.
2.13.1. Calibration#
The compass can be calibrated to the local magnetic conditions by calling
compass.calibrate()
To calibrate you need to tilt the micro:bit so that each pixel in the display turns red.
Warning
You need to calibrate your compass the first time it is used. It’s best to do this at the start of your script.
2.13.2. Orientation#
There are three functions for accessing the orientation data:
compass.get_x()compass.get_y()compass.get_z()
Each returns an integer with the magnetic field strength for the given axis in nano teslas.
2.13.3. Heading#
You can get a more natural heading reading by using
compass.heading()
which returns an integer in the range 0-360 representing the angle in degrees from north (0) in a clockwise direction.
Example#
from microbit import *
compass.calibrate()
# Try to keep the needle pointed in (roughly) the correct direction
while True:
heading = compass.heading()
print(heading)
sleep(200)