The MicroPython micro:bit module also has a compass object. This object has methods for working with the compass to detect the amount of magnetic force on each of the x, y and z axes as well as picking out a compass direction and the strength of the magnetic field around the device.
The compass has to be calibrated before it can give accurate readings. Calibration involves moving a dot to make a circle on the matrix. You get a smiling face image to show you that you have completed the calibration. Calibration is needed to compensate for tilt and uses accelerometer readings to calculate how to correct the compass readings to give an accurate bearing.
Getting A Bearing
With the following program, we can test the kind of values that we get for the compass heading. Make sure you click on the REPL button before you flash this program to the micro:bit. When you have completed the calibration, you should get 10 bearings a second printed to the console.
from microbit import * compass.calibrate() while True: bearing = compass.heading() print(bearing) sleep(100)
There is a compass.is_callibrated() method that you can use to check that calibration has taken place if this is something that you don't want to force the user to do until you are using it.
I'm not sure what you'd want to do with these. You can find out what they are. With the REPL window open, flash the following program to do that,
from microbit import * compass.calibrate() while True: x = compass.get_x() y = compass.get_y() z = compass.get_z() print ("x: " + str(x) + " y: " + str(y) + " z: "+ str(z)) sleep(100)
You can also use the compass.get_field_strength() method to get an integer that changes depending on the magnetic field around the device.
- Clearly, a compass with some sort of indicator on the matrix would be a decent project to be making from these techniques. Make sure you remember how hard it is to hold the device at an exact bearing and allow 15° or so either side of any heading you want the user to hold.
- You are probably programming your micro:bit in a rectangular room. Work out how to program it to detect when you are facing each of the walls of the room.
- You can use the idea of the last program to make a game. Mark a specific spot in a room by placing something there that it is ok to stand on. Write test programs to discover the compass headings of various objects placed and spaced out around the room so that each one is at a different heading. Design a matrix image to represent each of these objects. Now write a program that randomly chooses one of those images that the user must face. Enclose this logic in a repetition structure and make them do it over and over again. The running_time() method returns the number of milliseconds since the board was (re)started - this might prove useful in making a scoring system.