Home · Academy · Robotics & Coding · micro:bit · Project: Step Counter

Project: Step Counter

Build a step counter that uses the accelerometer with a threshold and filtering.

PROJECT COMPASS

What will you use this page for?

Core idea

In this project we use the micro:bit's accelerometer to build a simple step counter (pedometer) that counts each step, shows the total on the 5×5 LED display and resets with a button.

Evidence to produce

Complete the page task with your own input, test conditions and reasoning.

Control trap

Never tuning the threshold Everyone walks and holds the device differently. There is no single "correct" threshold; you have to find yours by testing. Forgetting the dead time (wait) If you do not add a sleep after counting a step, one step gets counted many times. This is the most common cause of the "over-counting"…

Next connection

Project: Wireless Score System

Module sources: Python Tutorial · Arduino Learn

LevelBeginner
Age10–16
Duration45–75 min
PrerequisitePython on the micro:bit
ContentProject guide · 1,974 words
Last updated

One-sentence summary

In this project we use the micro:bit's accelerometer to build a simple step counter (pedometer) that counts each step, shows the total on the 5×5 LED display and resets with a button.

Why it matters

The step counter on your phone or smartwatch is not really a mystery box. Inside it there is a sensor that your micro:bit also has: an accelerometer. This project lets you understand how those devices detect a "step" by building one with your own hands.

It is also a real engineering problem. A sensor gives raw data, but the thing we call a "step" is not a neat line in that data. Swaying while you walk, jumping, or even shaking the device on purpose can all confuse the counter. So throughout this project we will set up a threshold and a simple filter to reduce false counts. In other words, we take our first step into processing real-world sensor data.

The idea behind step detection

What does the accelerometer measure?

An accelerometer measures how quickly the device changes its motion. The micro:bit has three axes: X (left-right), Y (forward-back) and Z (up-down). We can read a number on each axis, measured in "milli-g" (1 g is roughly the pull of gravity).

Instead of a single axis, it is easier to measure the total shake using the combined force value. The micro:bit gives this to us directly:

When the device sits still, this value is around 1000 because of gravity. When you take a step, your body bobs up and down and the value spikes for a moment.

A step = a peak

While you walk, the combined force keeps rising and falling. Each step makes a peak in the graph. Our job is simple: count a step whenever the value rises above a certain threshold.

If we set the threshold too low, the device treats the tiniest wobble as a step and over-counts. If we set it too high, it misses real steps and under-counts. We will find the right threshold by testing. This is exactly where algorithms and filtering come in.

Building the program step by step

MakeCode block sequence

First we create a variable for the count. Then, in a forever loop, we check the acceleration.

on start
  set steps = 0
  show "0"
forever
  if <acceleration (strength) > 1500> then
    set steps = steps + 1
    show steps
    pause 50 ms
on button A pressed
  set steps = 0
  show "0"

The 1500 here is our threshold. The pause 50 ms is the first part of a simple filter we will explain next: it helps stop one step from being counted twice.

The MicroPython version

We can write the same logic in Python. The code looks different, but the idea is exactly the same.

from microbit import *

steps = 0
threshold = 1500
display.show("0")

while True:
    force = accelerometer.get_strength()
    if force > threshold:
        steps += 1
        display.show(str(steps))
        sleep(300)      # simple filter: wait a short time
    if button_a.was_pressed():
        steps = 0
        display.show("0")

accelerometer.get_strength() gives the combined force. sleep(300) waits 300 milliseconds after counting a step so that we do not count the same peak again.

Showing the count

display.show(str(steps)) scrolls the number across the LED display. If the number gets large (say 42) the digits flow across one by one. If you prefer, you can show it only when button B is pressed, keeping the screen calm while you walk:

if button_b.was_pressed():
    display.show(str(steps))

Testing and fixing a bug

Test scenarios

After you flash the code, try the micro:bit like this:

  1. Hold still: With the device still in your hand, the number should not go up.
  2. Walk 10 steps: Hold the device in your palm and count 10 steps. The number on screen should be close to 10.
  3. Reset: Press button A; the number should return to 0.
  4. Shake fast: Shake the device quickly and see how differently it counts compared to a real step.

The bug we hit: over-counting

On my first try I walked 10 steps but the screen showed 19 — almost double. The cause was clear: during the peak of a single step, the combined force crossed the threshold not once but several times. So one step was being counted as two or three.

I made two fixes:

threshold = 1800
# ...
    if force > threshold:
        steps += 1
        display.show(str(steps))
        sleep(350)      # dead time: do not count the same step again

When I tried again, 10 steps showed 11 on screen. Not perfect, but much more accurate. This is a real example of why filtering matters: raw sensor data + a little algorithm = a useful result.

Mini practice

Build your own step counter and try these tasks in order:

  1. Flash the MicroPython code above.
  2. Hold the device in your palm and walk exactly 20 steps, then note the number on screen.
  3. Set the threshold first to 1500, then to 2000, and walk the same 20 steps again. Which threshold gave you the closest result?
  4. Fill in a table:
Mini practice table
ThresholdReal stepsCounterDifference
150020??
180020??
200020??
  1. Once you find your best threshold, put the device in your pocket, walk for 30 seconds and check the result.

The goal is not a perfect number; it is to find the best threshold for your own body and where you carry the device by testing.

Project strengthening plan

A working demonstration is not enough for Project: Step Counter. A strong project also makes its aim, user, limits, test conditions and failed attempts visible. Use the context of a meter that shows light and temperature values on the LED matrix to produce a micro:bit program tested in the simulator and on the board, with test notes. Although the lesson aims to “Build a step counter that uses the accelerometer with a threshold and filtering”, do not present an unmeasured result as a confirmed success.

1. Project summary and scope

Write three sentences: What problem are you solving, who is affected by it, and what will the first version deliberately not do? Stating what is outside the scope does not weaken a project; it makes the project finishable. Describe the connection between The idea behind step detection and A step = a peak as the main assumption, then name the test that can confirm or reject it.

2. Acceptance criteria

Do not leave an acceptance criterion for “Project: Step Counter” as a vague statement such as “it works”. Choose an observable measure such as time, distance, correct trials, screen width or user steps. When direct measurement is difficult, record whether the same behaviour appears in three consecutive trials.

3. Test matrix

3. Test matrix table
TestConditionExpectedActual resultNext decision
NormalStandard input and complete setupThe core task is completedFill in during the testKeep it or make a small improvement
BoundaryLowest or highest accepted valueThe system remains stableFill in during the testReview the threshold or rule
ErrorMissing, wrong or unexpected inputA safe and clear responseFill in during the testAdd error handling
RepeatAt least three trials under the same conditionSimilar resultsFill in during the testInvestigate the source of inconsistency

4. Version log

For every version of “Project: Step Counter”, record the date, the one main decision changed, the reason and the test result. A first version that fails is evidence about which assumption involving The idea behind step detection or A step = a peak should be reconsidered. Remove personal information and private background details from images.

5. Presentation and self-review

Prepare a two-minute explanation of “Project: Step Counter”: the problem, the solution approach, the most important result for a meter that shows light and temperature values on the LED matrix, and the next step. Instead of saying the project is complete, state which part has been verified and which part still needs development.

Common mistakes

Never tuning the threshold

Everyone walks and holds the device differently. There is no single "correct" threshold; you have to find yours by testing.

Forgetting the dead time (wait)

If you do not add a sleep after counting a step, one step gets counted many times. This is the most common cause of the "over-counting" bug described above.

Making the wait too long

If you set a long wait like sleep(1000), you will miss real steps when walking fast. This time you under-count. Around 300–400 ms is usually a good start.

Not putting the counter in "on start"

If you write the variable and the first "0" inside the forever loop, the counter resets every pass and never grows. The start block runs once; the counter must be defined there.

Safety note

Lesson summary

Check questions

  1. Why is the combined force value not zero when the micro:bit is still?
  2. If we set the threshold too low, in which direction does the counter make a mistake?
  3. Why do we need to wait a short time (sleep) after counting a step?
  4. On our first try 10 steps showed 19; what was the reason?
  5. Which event did we use in the program to reset the counter?

Answers

  1. Gravity always acts on the device, so the combined force is around 1000 (1 g) even when it sits still.
  2. It treats even small wobbles as steps, so it counts more than the real number.
  3. The peak of a step can cross the threshold several times in a short moment; the wait (dead time) stops the same step from being counted again.
  4. Each step's peak crossed the threshold multiple times, so every step was counted a few times; we fixed it by raising the threshold and the wait time.
  5. We used the button A press event (button_a.was_pressed() / on button A pressed) to set the counter back to 0.

Source and verification note

For “Project: Step Counter”, verification focuses on whether the relationship between The idea behind step detection and A step = a peak remains consistent across examples. MakeCode and MicroPython names can vary slightly by version. Test in the simulator first; when external components are connected, check the board’s pin and voltage limits separately.

Next lesson

Project: Wireless Score System

Start QuizBack to micro:bit
QUESTION POOL

Reinforce this lesson with 10 questions

This lesson has a pool of 20 questions. Each attempt selects 10 and reshuffles the choices.