Test the Existing Tilt Compass

Example script: display_tilt_direction_with_leds

This script is from Your Turn: Display Tilt Direction.  It’s part of a chapter about using the micro:bit as a tilt radio controller for the cyber:bot robot.  Here we will just focus on measuring and displaying tilt.

  • Enter the script display_tilt_direction_with_leds into the micro:bit Python Editor.
  • Use the Send to micro:bit button to flash the script into the micro:bit.
# display_tilt_direction_with_leds

from microbit import *
import math

sleep(1000)

while True:
    x = accelerometer.get_x()
    y = accelerometer.get_y()

    angle = round( math.degrees( math.atan2(y, x) ) )
    needle = ( angle + 90 + 15 ) // 30

    print("angle =", angle, ", needle =", needle)
    display.show(Image.ALL_CLOCKS[needle])
    
    sleep(200)

 

Test the Existing Tilt Compass

  • Try holding the micro:bit vertically, and rotating it like a car’s steering wheel.  Verify that it points downward as you do that, like in the “This is down” picture.
  • Also try holding the micro:bit flat and then tip it in various directions (like the micro:bit tilt controller in the cyber:bot video).
  • In both cases, holding vertically and rotating, or holding flat and tilting the micro:bit, verify that it points down.

How It Works

The micro:bit uses its built-in accelerometer to measure tilt.  To learn more about how the micro:bit measures tilt, try Test Tilts.

The micro:bit displays the tilts using one of twelve elements in the Image.ALL_CLOCKS[] list.  Image.ALL_CLOCKS[0] points to 12 o’clock, Image.ALL_CLOCKS[1] points to 1 o’clock, Image.ALL_CLOCKS[2] points to 2 o’clock, and so on...  Learn more at Display Tilt Direction.

The micro:bit can also measure tilt angles, as shown in Measuring Rotation Angles.

The micro:bit uses equations from trigonometry to change X and Y axis accelerometer measurements into tilt angles.  Don’t worry, you don’t have to understand trigonometry to use this app.  But, if you’re curious there’s more about it here:  Did You Know? Trigonometry and Rotation Angles.