BBC micro:bit – Roll the Dice

diceIn this challenge we will code our BBC micro:bit to create a “rolling dice” animation.

Our code will generate random numbers between 1 and 6 to create the animation and will include 8 frames. The last frame will be the number picked up by the dice. Here is a preview of the animation (on an infinite loop):

bbc-micro-bit-roll-the-dice

You can recreate this digital dice using the BBC micro:bit website.

Building the code, step by step:

Our “rolling the dice” animation will start when the user presses the A button on the micro-bit.
micro-bit-button-a

To create the animation we will then use a loop (repeat 8 times):
micro-bit-repeat

For each frame we will generate a random number between 1 and 6 using the following code:
micro-bit-random-number

We will then check the value of this random number using an IF block:
micro-bit-if

To display this number as it will appear on a dice we will use the “show leds” block:
micro-bit-show-leds

We will repeat the last two steps for all the 6 possible faces of the dice by adding ELSE IF blocks to our IF block:
micro-bit-else-if

Finally we will add a pause between each frame (between each iteration of the loop):
micro-bit-pause

Final Code


Here is the complete code for our dice:
micro-bit-die-code

Did you like this challenge?

Click on a star to rate it!

Average rating 2.7 / 5. Vote count: 15

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: