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, name, and save display_tilt_direction_with_leds.  
  • Click the Send to micro:bit button.
# 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)
  • Check the results in the serial monitor.
  • 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
  • Click Send to micro:bit to 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.