Your Turn: Display Tilt Direction

With the tilt direction display mentioned in the Did You Know? section on the previous page, your script can display a needle that either points up or down.

Example Script:  display_tilt_direction_with_leds

  • Enter this script and save it as display_tilt_direction_with_leds.  
  • 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)
  • Open the terminal.
  • Try rotating and tilting your micro:bit in various directions, and verify that the display always points downward.
  • Change the first plus sign in
needle = ( ( angle + 90 ) + 15 ) // 30

      …to a minus sign:

needle = ( ( angle - 90 ) + 15 ) // 30
  • Flash the modified script into the micro:bit.
  • Try rotating and tilting your micro:bit in various directions again.
  • Verify that the display always points upward.