Step 1: Make it
What is it?
Make a tool for making sure pictures, shelves or work surfaces are level. The new micro:bit's built-in speaker makes it easy to improve your spirit level with audio feedback.
What you'll learn
- How to use the accelerometer sensor to measure angles
- What 'pitch' and 'roll' are
- How to combine sensor readings in two dimensions to find a level surface
How it works
- The micro:bit's accelerometer can measure angles of tilt in two directions: up and down (pitch) and side to side (roll). This project uses this to show when the micro:bit is level on the LED display and by making a sound, which could be useful when hanging a picture or making a work surface.
- A loop keeps the program constantly measuring the micro:bit's angle.
- If the accelerometer measures an angle of tilt between +5 and -5 degrees of both pitch and roll, the micro:bit must be reasonably level. It then shows a tick on the LED display output and plays a musical tone.
- To hear the tone attach headphones or a speaker to pin 0 and GND, or if you have a new micro:bit you will hear it on the built-in speaker.
- If either the pitch or the roll is outside the range +5 to -5 degrees, it shows a cross on the LED display and stops the sound.
What you need
- A micro:bit
- MakeCode or Python editor
- battery pack (optional)
Step 2: Code it
1from microbit import * 2import music 3 4# Uses accelerometer readings in the x and y axis 5# and also allows the micro:bit to be slightly off-level 6# to make it work better in practice 7while True: 8 if accelerometer.get_x() > -10 and accelerometer.get_x() < 10 and accelerometer.get_y() > -10 and accelerometer.get_y() < 10: 9 display.show(Image.YES) 10 music.play('C5:1') 11 sleep(200) 12 else: 13 display.show(Image.NO) 14
Step 3: Improve it
- Can you make the musical pitch change depending on the angle?
- Could you code an LED 'bubble' that moves around the screen like a real spirit level?
This content is published under a Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) licence.