You are going to learn how to make a timer, so that you can use it to challenge your friends!
Step 1: Setting up your timer
Let’s set your timer to 0 when buttons A and B are pressed together.
Go to jumpto.cc/mb-new to start a new project in the Code Kingdoms editor. Call your new project ‘Timer’.
onStartevent (including the comment) into the bin, as you don’t need it.
- Click ‘Add Event’ and create a new
- Click the ‘Library’ tab and then ‘Globals’, and create a new variable called
- When buttons A and B are pressed together, you want the
timeto be set to
0. To do this, drag your
timevariable into your
# numberand enter
Here’s how your code should look:
You should also display the
time. To do this, drag in a
sayblock, click the
valuearrow and choose your
Click ‘run’ to test your code. Press the ‘A+B’ button (below the micro:bit) to set your timer to 0.
Step 2: Starting and stopping your timer
Let’s use button A to start your timer, and button B to stop it.
- Your timer should start when button A is pressed. Add a new
onPressAevent to your script.
- The timer should count up as long as button B has not been pressed. To do this, first drag a
whileblock into your new
- Click the
testarrow, and choose
You can then drag a
buttonBPressedblock into the
valuegap in your
Any code inside this
whileloop will be run repeatedly, as long as button B has not been pressed.
Next, you want to add 1 to your
timevariable every second (1 second = 1000 ms). Add a
waitblock to make your timer wait for 1 second.
- To increase your
timevariable, drag in the variable, click the
updatearrow and click
left + right.
- Click the
leftarrow and choose your
- Click the
rightarrow and enter
1. This will add 1 to the current value of
- Finally, you’ll need to display the updated
timevariable. Here’s how your code should look:
Click ‘run’ to test your code.
- Press buttons A and B together to set your timer to 0
- Press button A to start your timer
- Press (and hold) button B to stop your timer
Challenge your friends!
Use the timer to challenge your friends. For example, you could see how long it takes them to say the alphabet backwards, or name 10 capital cities.
Challenge: Counting Down
Can you create a new timer, that counts down to 0? Here’s how your new timer should work:
Pressing buttons A and B together should set your
Pressing button B should add 1 to your timer
Pressing button A should take 1 from your
timevariable until it gets to 0. This means you’ll need a
whileloop that runs as long as the
timeis greater than (