Create a working stopwatch!
- 1 x micro:bit
- 1 x Breakout Board
- 1 x OLED
Insert the micro:bit into the Breakout Board and connect the OLED to the Breakout Board, making sure that the pins are correctly aligned with the slots, GND to GND, VCC to VCC etc. It should look like the picture when you're done.
1x Micro:bit 1x OLED 1x Breakout Board
Before we get into actual coding... you have to download an extension. Scroll down to the ‘Advanced’ tab and look for ‘Extensions’. Click on it and search ‘tinker’. Download the extension showed in the picture.
Let's start coding! Go into the Variables tab and create two new variables, counter and diff. We will use counter to store the number of seconds, and change counter by diff (it will either be 1 or 0) .
Get an "on start" block. Under it we will write some code to initialize everything. Initialize the OLED display with height 64 and width 128, set diff to 1, set counter to 0 and display it on the OLED.
Now, we have to write some conditions. We want to use button A to start the stopwatch, button B to stop it, and A+B to reset. Let's look at the code in the next step.
When button A is pressed, set diff to 1 (we want to change counter by 1 each time). Now we want to start a while loop, so that it will loop as long as diff is 1. In the loop, pause for 750 ms before changing counter by diff, clear the OLED display, and show counter. 1 second is 1000 ms, so we wait for 750 ms, and give the OLED 250 ms to display the counter. This way, the counter will be increasing by 1 every second (that's what a stopwatch does!).
When button B is pressed, set diff to 0 and clear the display, then display counter. This will stop the counter from increasing, and keep displaying the current value of the counter.
When A+B is pressed, set diff and counter to 0. Then clear the display and display the value of the counter (which is 0). This stops the counter from increasing, resets it to 0 and displays it.