Coding Ireland STEM Report 2024 Have Your Say
Microbit
Beginner
45 mins
85 points
What you need:
Computer/laptop
Microbit

Building a Digital Dice

In this exciting lesson, you will learn how to build a digital dice using Microbits! Through this project, you will practice your coding skills and create a fun, interactive game tool.
Learning Goals Learning Outcomes Teacher Notes Lesson Files

1 - Creating a New Project

Start by creating a new project. Visit the Microbit coding website at https://makecode.microbit.org/ and click on 'New Project'. Give the project a suitable name, such as 'Digital Dice'.

2 - Create a 'roll' variable

We will need a variable to store what number we roll. Create a variable called roll and we will use this in the next step.

3 - Coding the Dice Shake

In this step, you will code the Microbit to generate a random number when it's shaken. This simulates the action of shaking a dice to get a number. Add the following code:

input.onGesture(Gesture.Shake, function () { let roll = Math.randomRange(1, 6) })

This code uses an input event tied to the 'Shake' gesture, and generates a random number between 1 and 6, storing it in the variable 'roll'.


4 - Displaying the Dice Roll

Next, you will code the Microbit to display the number that was generated from the dice roll. Add the following code:

input.onGesture(Gesture.Shake, function () { 
let roll = Math.randomRange(1, 6) 
basic.showNumber(roll) 
})

This code extends the previous one by using the 'showNumber' function to display the 'roll' variable on the Microbit's LED matrix.


5 - Testing the Digital Dice

Now, it's time to test your digital dice! If you have a physical Microbit, you can download the code onto it. This step is optional. To download, click the 'Download' button in the MakeCode editor and follow the instructions. If you don't have a Microbit, use the simulator on the website to test your code. Shake the Microbit (or click 'shake' in the simulator) and see if a random number displays on the LED matrix.


Unlock the Full Learning Experience

Get ready to embark on an incredible learning journey! Get access to this lesson and hundreds more in our courses.

Copyright Notice
This lesson is copyright of Coding Ireland. Unauthorised use, copying or distribution is not allowed.
🍪 Our website uses cookies to make your browsing experience better. By using our website you agree to our use of cookies. Learn more