MicroPython — sensors: acceleration, tilt and a pedometer
The micro:bit has a built-in accelerometer — a sensor that measures movement, tilt and acceleration. In this lesson you will learn how to:
- detect the tilt of the device
- react to movement (shake)
- make a simple step counter (pedometer)
These are the same ideas you may have already seen in MakeCode, but now we do them in MicroPython.
Detecting the tilt of the micro:bit
The MicroPython function accelerometer.get_x()
measures the tilt along the X axis.
from microbit import *
while True:
x = accelerometer.get_x()
if x > 300:
display.show(Image.ARROW_E)
elif x < -300:
display.show(Image.ARROW_W)
else:
display.clear()
When you tilt the micro:bit to the left or right, an arrow will appear on the screen.
Detecting movement (shake)
MicroPython has the method was_gesture()
that checks whether a certain movement has happened.
from microbit import *
while True:
if accelerometer.was_gesture("shake"):
display.show(Image.SURPRISED)
sleep(1000)
display.clear()
Shake the micro:bit — a surprised face will appear.
A simple step counter (pedometer)
By combining sensors and variables we can make a movement counter.
from microbit import *
steps = 0
while True:
if accelerometer.was_gesture("shake"):
steps += 1
display.show(str(steps))
sleep(500)
Every stronger movement increases the number of steps. This is the basis of a pedometer.
Comparison with the MakeCode micro:bit
If you worked with the micro:bit in the MakeCode environment, you used these functions through blocks:
- on shake
- acceleration (x)
- tilt left / right
You can compare:
- The MakeCode lesson (grades 5–6): The accelerometer in MakeCode
- The MicroPython version (grades 7–8): this lesson
The idea is the same — only the way of writing the program is different.
Why are sensors important?
- they are used in games, sports apps and measurements
- they are the basis for projects with robots
- they help you practise working with conditions and variables
Advanced work with the accelerometer
The accelerometer can measure acceleration along three axes:
get_x()— left/rightget_y()— forwards/backwardsget_z()— up/down
Example 1 — Detecting tilt in all directions
from microbit import *
while True:
x = accelerometer.get_x()
y = accelerometer.get_y()
if x > 300:
display.show(Image.ARROW_E)
elif x < -300:
display.show(Image.ARROW_W)
elif y > 300:
display.show(Image.ARROW_S)
elif y < -300:
display.show(Image.ARROW_N)
else:
display.clear()
Now the micro:bit reacts to tilt in four directions.
Example 2 — A step counter with a reset button
from microbit import *
steps = 0
while True:
if accelerometer.was_gesture("shake"):
steps += 1
display.show(str(steps))
sleep(500)
if button_a.was_pressed():
steps = 0
display.show("0")
Button A resets the number of steps.
Example 3 — A goal of 10 steps
from microbit import *
steps = 0
while True:
if accelerometer.was_gesture("shake"):
steps += 1
display.show(str(steps))
sleep(400)
if steps == 10:
display.show(Image.HAPPY)
sleep(1500)
steps = 0
When you reach 10 movements, a smiley appears.
Example 4 — A digital spirit level
from microbit import *
while True:
x = accelerometer.get_x()
y = accelerometer.get_y()
if -100 < x < 100 and -100 < y < 100:
display.show(Image.YES)
else:
display.show(Image.NO)
If the device is almost level — a ✔ is shown.
Tasks for independent work
Task 1 — Tilt + LED animation
Make a program that:
- Shows an arrow when the tilt is greater than 300
- Shows a heart when the device is level
Task 2 — A step counter with a goal of 20
When you reach 20 steps:
- Show the message "BRAVO"
- Reset the counter
Task 3 — A digital game
Combine:
- button A
- tilting left/right
Idea: move a dot across the screen by tilting.
Task 4 — An alarm for a strong movement
If the acceleration along the X axis is greater than 800:
- Show an exclamation mark
- Flash the screen 3 times
Solutions of the tasks (for the teacher)
Solution 1 — Tilt + LED animation
from microbit import *
while True:
x = accelerometer.get_x()
if x > 300:
display.show(Image.ARROW_E)
elif x < -300:
display.show(Image.ARROW_W)
else:
display.show(Image.HEART)
If there is no larger tilt, a heart is shown.
Solution 2 — A step counter with a goal of 20
from microbit import *
steps = 0
while True:
if accelerometer.was_gesture("shake"):
steps += 1
display.show(str(steps))
sleep(400)
if steps == 20:
display.scroll("BRAVO")
steps = 0
When 20 movements are reached, the message is shown and the counter is reset.
Solution 3 — Moving a dot by tilting
from microbit import *
x = 2
y = 2
while True:
display.clear()
display.set_pixel(x, y, 9)
tilt = accelerometer.get_x()
if tilt > 300 and x < 4:
x += 1
elif tilt < -300 and x > 0:
x -= 1
sleep(200)
The dot moves left/right when the device is tilted.
Solution 4 — An alarm for a strong movement
from microbit import *
while True:
x = accelerometer.get_x()
if x > 800 or x < -800:
for i in range(3):
display.show("!")
sleep(200)
display.clear()
sleep(200)
If the acceleration is strong, the exclamation mark flashes three times.
Mini project — A fitness band
Let us make a simple "fitness band" that:
- counts steps
- has a daily goal (e.g. 15 steps)
- can be reset with button A
- shows the result with button B
How will we count steps?
We will not use only shake, because it is not precise.
Instead we will measure a sudden change of acceleration along the X axis.
If the value is greater than a certain limit — we count a step.
The program
from microbit import *
steps = 0
goal = 15
while True:
x = accelerometer.get_x()
# Detecting a stronger movement
if x > 700 or x < -700:
steps += 1
display.show(str(steps))
sleep(300) # a short pause so that the same movement is not counted several times
# Checking the goal
if steps >= goal:
display.scroll("GOAL!")
display.show(Image.HAPPY)
sleep(1000)
steps = 0
# Button A resets the number
if button_a.was_pressed():
steps = 0
display.show("0")
# Button B shows the current number
if button_b.was_pressed():
display.scroll(str(steps))
How does the project work?
- The micro:bit measures the acceleration all the time
- If the movement is strong enough → it increases the number
- When it reaches the goal → it shows a message
- Button A resets
- Button B checks the result
Why do we use sleep(300)?
Without a pause, the micro:bit could count several steps for one single movement. This is a simple way of filtering noise.
An advanced version (a challenge)
Try to improve the project:
- Set the goal to 30 steps
- Add an animation when the goal is reached
- Save the record (the largest number of steps)
How does filtering movement work?
The accelerometer measures acceleration all the time. The values change quickly and often contain "noise" (small random changes).
If we counted every small movement, the counter would grow too fast. That is why we introduce a threshold.
A graphic explanation
Acceleration (X axis)
900 | * *
800 | * * *
700 |----------------------------- ← THRESHOLD
600 | *
500 | *
400 |
300 | *
200 |
100 |
0 |____________________________________
time →
We count only values above 700 as a step.
We ignore all the values below the threshold.
An example without filtering (a bad example)
from microbit import *
steps = 0
while True:
x = accelerometer.get_x()
if x > 100:
steps += 1
display.show(str(steps))
⚠ The problem: the counter grows too fast because 100 is reached by small oscillations.
An example with filtering (a good example)
from microbit import *
steps = 0
THRESHOLD = 700
while True:
x = accelerometer.get_x()
if x > THRESHOLD or x < -THRESHOLD:
steps += 1
display.show(str(steps))
sleep(300)
Why do we also use sleep()?
When a strong movement happens, the signal lasts a few milliseconds. Without a pause, the program could count it several times.
Sleep makes a small "rest" — and in this way imitates a real pedometer.
An experiment for the class
Let the students try different threshold values:
- 500 — a sensitive device
- 700 — medium sensitivity
- 900 — a very rough filter
Discussion: which value is the most realistic? Why?
An advanced visualisation (a bonus demonstration)
from microbit import *
while True:
x = accelerometer.get_x()
level = abs(x) // 200 # scaling
if level > 4:
level = 4
display.clear()
display.set_pixel(2, 4-level, 9)
sleep(100)
The dot moves up and down depending on the strength of the movement. This is a simple "mini graph" of the signal.
Exercises — working with motion sensors
The following exercises help you practise working with the accelerometer and develop your own MicroPython programs that react to the movement of the device.
Exercise 1 — A tilt counter
Task:
Show the number of tilts to the left and the number of tilts to the right on the LED screen.
When the user tilts the micro:bit to the left, the left counter increases. When they tilt it to the right, the right counter increases.
Tip: use:
accelerometer.get_x()- variables for counting
display.scroll()
An example solution:
from microbit import *
left = 0
right = 0
while True:
x = accelerometer.get_x()
if x < -300:
left += 1
display.scroll("L:" + str(left))
sleep(500)
if x > 300:
right += 1
display.scroll("R:" + str(right))
sleep(500)
Exercise 2 — A movement alarm
Task:
Show a warning sign when the device is shaken.
MicroPython has a built-in function that detects the shake event.
Tip: use:
accelerometer.was_gesture("shake")Imageor text
An example solution:
from microbit import *
while True:
if accelerometer.was_gesture("shake"):
display.show(Image.SKULL)
sleep(1000)
display.clear()
Challenge (an advanced task)
Try to make an alarm that:
- switches on the alarm after 3 shakes in a row
- or shows different symbols for different movements
This is an excellent basis for projects such as:
- an anti-theft alarm
- a pedometer (step counter)
- a game controller
Mini quiz — MicroPython motion sensors
Click the quiz and check whether you understand working with the accelerometer, tilt and the shake gesture in MicroPython.
Open the quiz
Mini quiz: MicroPython sensors
1. Which function reads the tilt along the X axis?
2. What does the value X > 0 mean?
3. Which function detects a shake?
4. Which command shows scrolling text on the LED screen?
5. Which value means that the device is almost level?
Quiz — MicroPython motion sensors (scoring)
Solve the quiz and check your knowledge of the accelerometer, tilt and the shake gesture. At the end you will get the number of points and the percentage.
Visualising sensor data in Python Processing
MicroPython lets you read data from sensors, but the real potential comes when we show that data as graphics on the computer. We can do that with the tool Processing (Python Mode).
For example, we can show:
- a chart of the number of steps in real time
- a visualisation of the tilt of the device
- an animation that reacts to movement
- interactive projects and games
The data is sent from the micro:bit over the USB cable using serial communication, and Processing turns it into graphics.
Find out how to connect MicroPython and Processing in the next lesson:
MicroPython and Processing — serial communication and data visualisation (SR)
If you want to learn how to make graphics and animations in Processing, see the complete course:
Python and Processing — creative programming (the complete course)
