micro:bit Digital Dice: Shake to Roll
Shake the board: the dice rolls for a moment, then stops on a random face from 1 to 6. The accelerometer feels the shake (was_gesture) and random.choice picks the face. No extra parts are needed.

Video
Circuit Diagram

Source Code
1# ─────────────────────────────────────────
2# BlueGrays · bluegrays.com
3# micro:bit Digital Dice: Shake to Roll
4# ─────────────────────────────────────────
5# Shake the board: the dice rolls for a moment, then stops on a random
6# face from 1 to 6. The accelerometer inside the board feels the shake. No
7# extra parts are needed.
8#
9# Pins:
10# LED -> Onboard 5x5 LED display
11# ACCEL -> Onboard accelerometer
12
13from microbit import *
14import random
15
16# ============ SETTINGS ============
17ROLL_STEPS = 8 # Faces shown while rolling
18ROLL_MS = 80 # Time for each face (ms)
19LOOP_MS = 50 # Loop pause (ms)
20
21# The six faces of the dice. Each row is one row of the display; 9 is a lit LED, 0 is off.
22DICE = [
23 Image("00000:00000:00900:00000:00000"),
24 Image("00009:00000:00000:00000:90000"),
25 Image("00009:00000:00900:00000:90000"),
26 Image("90009:00000:00000:00000:90009"),
27 Image("90009:00000:00900:00000:90009"),
28 Image("90009:00000:90009:00000:90009"),
29]
30
31display.show(DICE[0])
32
33while True:
34 if accelerometer.was_gesture("shake"):
35 for i in range(ROLL_STEPS):
36 display.show(random.choice(DICE))
37 sleep(ROLL_MS)
38 display.show(random.choice(DICE)) # Result
39 sleep(LOOP_MS)
40FAQ
Is the dice really fair?
Yes. random.choice picks one of the six faces in the list with equal chance, and earlier throws do not affect the next one. We ran the code 600 times on a computer and each face came up about 100 times. Getting the same number twice in a row is normal; real dice do it too.
Can I show two dice?
The 5x5 display is too small for two dice side by side. The easy way is to show two numbers one after the other: write the result line twice with sleep(1000) in between. You could also add the two numbers and scroll the total with display.scroll.
How do I put this code on the micro:bit?
The code is MicroPython. Open the micro:bit Python Editor (python.microbit.org) on a computer, delete the code that is there and paste this one. Connect the board with a USB cable and press Send to micro:bit. If that button does not work, use Save to download the .hex file and copy it to the drive called MICROBIT. You can rebuild the same project with blocks in MakeCode, but this code cannot be pasted there.
Does it work on the older micro:bit (V1) too?
The code is written for the micro:bit V2. Projects that only use the LED display, buttons A and B and the accelerometer also run on a V1. The speaker, the microphone and the touch logo exist only on the V2, so code that uses them gives an error on a V1. If your board has a speaker on the back and a gold logo on the front, it is a V2.
