Before clicking the tips bags below, please take a breath and try again by yourself... :-)
START A BIT > Projects Library > PJ005: Digital counter with Micro:bit > This page
You need a variable to help remembering the counting, use "Variables -> Make a variable... ", give it a name, e.g. "counter", then you see below 3 blocks available to manipulate this new variable, to increase/decrease it, or use it.
To get the button input, use "Input -> on button... pressed"
To show the counter result on Micro:bit built-in LED matrix, use "Basic -> show number...". Drag your variable block into the white vacancy, it will display the value in LED matrix.
To link the logic, you need a if-else block and logic judgement block as well, use "Logic -> Conditionals -> if... then..." and "Logic -> Comparison -> ... = ..."
Of course, you need "on start" and "forever" blocks to set it run in a proper manner. Not both needed.
Before using the variable, remember to set an initial value on start! Note, this doesn't display anything on the LED matrix yet... you need to fix it later.
Use below 2 block, drag the variable into the vacancy of "show number..."
After done, it looks like below. This combined block will be reused in several places, just duplicate it.
Now, you should add this displaying to the "on start", so it will display "0" at the beginning.
This it is, looks simpler than imagined, eh? By this, please think hard to figure out the button B part.
Button B part seems easy, duplicate the button A part, and change to decrease. This is a good, but not enough, remember the requirement wants to avoid decreasing to minor counting when reaching 0, try to think how to fix basing on this.
By far, you already have a first version of working counter! Button A to increase, button B to decrease, always display the latest counting on LED matrix.
Is it interesting to download to Micro:bit to test before next steps below?
There are many ways to implement this function. These are some of the solutions we find from our students, for your reference.
In the "forever" block, put an if-else, hard reset the variable to "0" when it becomes less than 0.
In the "on button B pressed" block, before displaying the counting, put an if-else into hard reset the variable to "0" when it becomes less than 0.
In the "on button B pressed" block, as the first thing, check if the variable is 0, if yes, do nothing, if no, let it go normally to decrease and display.
Think about it, below is the example of the 3rd solution, which is more reasonable logically, and with the least waste of actions.
Here it is, we believe you can figure out by yourself.
These are all needed for this program.
This is a ready-baked take away in MakeCode, you can directly download to your Micro:bit to test.