Compass simulation
When you run a program that in the simulator, click and drag the compass needle on the screen to change the compass heading.
Find which direction on a compass the micro:bit is facing.
The micro:bit measures the compass heading from 0
to 359
degrees with its magnetometer chip. Different numbers mean north,
east, south, and west.
input.compassHeading();
0
to 359
degrees, which means the compass heading. If the compass isn’t ready, it returns -1003
.This program finds the compass heading and stores it in the
degrees
variable.
let degrees = input.compassHeading()
When you run a program that in the simulator, click and drag the compass needle on the screen to change the compass heading.
This program finds the compass heading and then shows a letter that means whether the micro:bit is facing north (N), south (S), east (E), or west (W).
let degrees = 0
basic.forever(() => {
degrees = input.compassHeading()
if (degrees < 45) {
basic.showArrow(ArrowNames.North)
} else if (degrees < 135) {
basic.showArrow(ArrowNames.East)
} else if (degrees < 225) {
basic.showArrow(ArrowNames.South)
} else if (degrees < 315) {
basic.showArrow(ArrowNames.West)
} else {
basic.showArrow(ArrowNames.North)
}
})
Every time you start to use the compass (for example, if you have just turned the micro:bit on), the micro:bit will start a calibrate compass (adjust itself). The calibration step will ask you to draw a fill pattern on the screen by tilting the micro:bit.
If you are calibrating or using the compass near metal, it might confuse the micro:bit.
Keep the calibration handy by running it when the user pressed A+B.
input.onButtonPressed(Button.AB, () => {
input.calibrateCompass();
})