GoalTrace a micro:bit program that counts button presses with a variable and resets the count to 0 when the equal-to test is true.
New words
counter · a variable that goes up by 1 each time something happensreset · to set a variable back to its starting value, often 0change by · a block that adds a number to a variableon start · a block whose blocks run once when the program begins
Explanation
A counter is a variable that counts how many times something happens. It must start at a known number, usually 0. The ‘set variable to 0’ block does this when the program starts. Each press runs ‘change variable by 1’, which adds 1 to the counter. An equal-to test then checks whether the counter has reached the limit. If it has, the program shows a message and resets the counter to 0. If the reset is missing, the counter goes past the limit and the equal-to test is never true again.
Block
What it does
Counter before → after
set [count] to 0
replaces the value with 0
5 → 0
change [count] by 1
adds 1
5 → 6
change [count] by -1
takes 1 away
5 → 4
(count) = (5)
only asks a question
5 → 5
Worked examples
A bell counter starts at 0. Each press of button A adds 1. When it reaches 4 the board shows the word Break and resets. Until then it shows the count.
Press
rings after change
rings = 4?
Display
1
1
false
1
2
2
false
2
3
3
false
3
4
4
true
Break (rings reset to 0)
5
1
false
1
6
2
false
2
Trace six presses. After press 4 the reset makes the count start again.
Press
rings
rings = 4?
Display
3
3
false
3
4
4
true
Break
5
5
false
5
6
6
false
6
Suppose the reset block is missing. The count passes 4 and the test is never true again, so Break shows only once.
Class activity
Counting claps (pairs). Player A claps and Player B holds a card showing the counter. Start the card at 0 and turn it up by 1 for each clap. When the card shows 4, B says ‘Break!’ and turns the card back to 0. Do 10 claps. What does the card show at the end? Try again with a limit of 3, and write down what changes.
Practice
1
The goal counter starts at 0. Button B is pressed 5 times. What does the board show on each press, and what is goals at the end?
Presses: 1, 2, happy face (goals reset to 0), 1, 2. At the end goals is 2.
2
A counter starts at 0 and goes up by 2 on each press. The test is ‘counter = 5’. Will the test ever be true? Why?
No. The counter shows 2, 4, 6, 8 and so on, so it jumps over 5. An equal-to test needs the exact number.
3
The program should count presses up to 3, but it always shows 1. Find the mistake and say how to fix it.
The block that sets laps to 0 is inside the button block, so laps is reset on every press and is always 1 after the change. Move it to the on start block.
4
Write an algorithm for a drink counter. Button A adds 1. When the count is 3 it shows the word Full and resets.
1 Start when button A is pressed. 2 Change count by 1. 3 If count = 3, then 3.1 show the word Full and 3.2 set count to 0. 4 Else show the number count. (The count is set to 0 at the start.)