micro:bit Spirit Level: A Dot That Slides as You Tilt
Tilt the board and the lit dot slides toward the lower edge like a marble; when the dot is in the middle the surface is level. The accelerometer measures the tilt (get_x, get_y) and set_pixel lights the dot. No extra parts are needed.

Video
Circuit Diagram

Source Code
1# ─────────────────────────────────────────
2# BlueGrays · bluegrays.com
3# micro:bit Spirit Level: A Dot That Slides as You Tilt
4# ─────────────────────────────────────────
5# Tilt the board and the lit dot slides toward the lower edge like a
6# marble. When the dot sits right in the middle the board is level. The
7# accelerometer inside the board measures the tilt. No extra parts are
8# needed.
9#
10# Pins:
11# LED -> Onboard 5x5 LED display
12# ACCEL -> Onboard accelerometer
13
14from microbit import *
15
16# ============ SETTINGS ============
17TILT_MAX = 400 # At this tilt the dot reaches the edge
18LOOP_MS = 50 # Loop pause (ms)
19
20
21# Turns a tilt value (from -TILT_MAX to TILT_MAX) into an LED position from 0 to 4.
22def to_led(tilt):
23 position = (tilt + TILT_MAX) * 5 // (2 * TILT_MAX)
24 return max(0, min(4, position))
25
26
27while True:
28 x = to_led(accelerometer.get_x()) # Left-right tilt
29 y = to_led(accelerometer.get_y()) # Front-back tilt
30 display.clear()
31 display.set_pixel(x, y, 9)
32 sleep(LOOP_MS)
33FAQ
Why does the dot slide down instead of up like a bubble?
In a real spirit level the air bubble moves to the higher side. Here the dot acts like a marble and rolls to the lower side, which feels more natural. If you want a bubble, change tilt + TILT_MAX inside to_led to TILT_MAX - tilt.
How precise is the level?
With only 5 positions on the display it is a rough measurement. With TILT_MAX at 400 the dot stays in the middle up to a tilt of about 5 degrees. Set TILT_MAX to 100 and the dot moves at much smaller tilts, so the level gets more sensitive.
How do I put this code on the micro:bit?
The code is MicroPython. Open the micro:bit Python Editor (python.microbit.org) on a computer, delete the code that is there and paste this one. Connect the board with a USB cable and press Send to micro:bit. If that button does not work, use Save to download the .hex file and copy it to the drive called MICROBIT. You can rebuild the same project with blocks in MakeCode, but this code cannot be pasted there.
Does it work on the older micro:bit (V1) too?
The code is written for the micro:bit V2. Projects that only use the LED display, buttons A and B and the accelerometer also run on a V1. The speaker, the microphone and the touch logo exist only on the V2, so code that uses them gives an error on a V1. If your board has a speaker on the back and a gold logo on the front, it is a V2.
