Skip to content

Spirit Level

Level Beginner
Board V1 & V2
Parts micro:bit

What you'll build

Tilt the micro:bit and a bright LED rolls to the lowest side, like a ball on a tray. When the board is flat, a target appears in the middle.

Code

12 spirit-level.py
'''
Example: Rolling-ball spirit level with the accelerometer in micro:bit
By: Meqdad Darwish
'''
from microbit import *

LEVEL = Image("00000:"
              "03330:"
              "03930:"
              "03330:"
              "00000")


def to_led(reading):
    # Tilt in milli-g (about -1024 to 1024) -> LED column/row 0-4, flat = 2
    return min(4, max(0, 2 + (reading + 150) // 300))


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

    if x == 2 and y == 2:
        display.show(LEVEL)
    else:
        display.clear()
        display.set_pixel(x, y, 9)
    sleep(50)

How it works

  • accelerometer.get_x() and get_y() measure tilt in milli-g: about 0 when flat and ±1024 when that edge points straight down. Tilt right and x goes positive. Tilt the pin edge down and y goes positive.
  • to_led() turns each reading into an LED position: every 300 milli-g of tilt moves the ball one LED from the middle, and min/max keep it on the 5×5 grid.
  • display.set_pixel(x, y, 9) lights one LED at full brightness. When the ball is centred, the custom LEVEL image shows a dim ring around it.

Try this next

  • Make it more sensitive by changing 300 to 150.
  • Turn it into a maze game: avoid "wall" pixels while you roll the ball to a goal.
  • Use accelerometer.was_gesture("face down") to switch the level off when the board is turned over.