Step Counter (II)
Put our micro:bit’s memory to work by using variables to create a device that counts our steps.
- 1 x micro:bit
- 1 x USB cable
- 1 x battery pack
Open your MakeCode Editor, and click on the Variable Drawer. Then, click on the Make a Variable button and create a variable called "counter".
Notice how 3 new blocks appear: your variable block, the set variable to_ block and the change variable by_ block.
Next, take the show number block from the basic drawer and place it inside the forever block. Then, navigate to the Variables drawer, pick out a counter block and place it inside the show number_ block. This lets our micro:bit check the current value of the variable - that will be our latest number of steps.
To increase the number of steps, we will need an event that triggers it. The closest gesture to walking would be an on shake event.
In the Input drawer, take a on shake block and place a change counter by_ block inside it. By default this changes the value of our variable by 1, on a shake. This tells our Microbit to increase our steps when we walk!
Finally, when we’ve completed our walk, we can reset the counter value with the following:
Take a on button A+B pressed block from the Input Drawer and place a set counter to_. block inside it. Change the value to 0. This resets the counter value to 0 whenever button A and B is pressed at the same time!
There you go, our step counter is finished! Attach a battery pack to your micro:bit and secure it to your leg. Try walking around the room and count how many steps you’ve taken!