In this lesson, you'll create a simple step counter pedometer using your Micro:bit's accelerometer to detect shakes as steps. You'll track the number of steps with a variable, use a loop to continuously monitor for movement, and add a way to reset the count. This project reinforces using control structures like loops and conditionals, and data types for accumulating values like integers.
By the end of this lesson, you'll have a working pedometer that counts steps when you shake the Micro:bit. Open the Micro:bit Python editor at python.microbit.org and start a new project.
In this step, we'll import the necessary module. We need the microbit module to access the hardware, including the accelerometer and display.
Start by adding the following complete code to your editor:
from microbit import *
Next, we'll create a variable to store the step count. Variables are useful for accumulating values, like an integer that increases with each step. We'll start it at 0 and display a ready message.
Update your code to the following complete version:
from microbit import *
steps = 0
display.scroll("Ready")
Now, let's add a loop to continuously check for shakes. We'll use a while True
loop, which runs forever, to monitor the accelerometer. Inside the loop, we'll check if a shake gesture occurred.
The accelerometer.was_gesture('shake')
function returns True
if a shake has been detected since the last check, and it resets after being called.
Update your code to this complete version:
from microbit import *
steps = 0
display.scroll("Ready")
while True:
if accelerometer.was_gesture('shake'):
display.scroll("Shake detected")
sleep(100)
sleep(100)
adds a short delay to prevent the loop from running too quickly. Test by shaking multiple times.Let's increment the steps variable each time a shake is detected and display the current count. This uses the +=
operator, which adds a value to the variable and assigns the result back (e.g., steps += 1 is like steps = steps + 1), to accumulate the integer value.
Update your code to this complete version, replacing the temporary message with the increment and display:
from microbit import *
steps = 0
#display.scroll("Ready")
while True:
if accelerometer.was_gesture('shake'):
steps += 1
display.scroll(steps)
sleep(100)
if
inside the loop checks the condition, and the variable accumulates the count.