RaspberryPi dice project

Here’s a simple dice (ok, die) project for the Raspberry Pi SenseHAT – it senses a shake by measuring the G-force on the accelerometer. If the G-force goes above 1.4, it generates a random number between 1 and 6 and displays a dice (die) pattern. I chose 1.4 so it’s not too sensitive – you have to give it a decent shake, and I put in a small sleep statement so it doesn’t do multiple rolls in one go.

It’s inspired by this BBC Microbit project – but then I’m still waiting for my own Microbit…

Here’s the Python code:

from sense_hat import SenseHat
import time
import random

sense = SenseHat()

sense.clear()

sense.show_message("Shake to roll!")

b = [0, 0, 0]
g = [0, 255, 0]
r = [255, 0, 0]

one = [
b,b,b,b,b,b,b,b,
b,b,b,b,b,b,b,b,
b,b,b,b,b,b,b,b,
b,b,b,g,g,b,b,b,
b,b,b,g,g,b,b,b,
b,b,b,b,b,b,b,b,
b,b,b,b,b,b,b,b,
b,b,b,b,b,b,b,b,
]

two = [
b,b,b,b,b,b,b,b,
b,g,g,b,b,b,b,b,
b,g,g,b,b,b,b,b,
b,b,b,b,b,b,b,b,
b,b,b,b,b,b,b,b,
b,b,b,b,g,g,b,b,
b,b,b,b,g,g,b,b,
b,b,b,b,b,b,b,b,
]

three = [
g,g,b,b,b,b,b,b,
g,g,b,b,b,b,b,b,
b,b,b,b,b,b,b,b,
b,b,b,g,g,b,b,b,
b,b,b,g,g,b,b,b,
b,b,b,b,b,b,b,b,
b,b,b,b,b,b,g,g,
b,b,b,b,b,b,g,g,
]

four = [
b,b,b,b,b,b,b,b,
b,g,g,b,b,g,g,b,
b,g,g,b,b,g,g,b,
b,b,b,b,b,b,b,b,
b,b,b,b,b,b,b,b,
b,g,g,b,b,g,g,b,
b,g,g,b,b,g,g,b,
b,b,b,b,b,b,b,b,
]

five = [
g,g,b,b,b,b,g,g,
g,g,b,b,b,b,g,g,
b,b,b,b,b,b,b,b,
b,b,b,g,g,b,b,b,
b,b,b,g,g,b,b,b,
b,b,b,b,b,b,b,b,
g,g,b,b,b,b,g,g,
g,g,b,b,b,b,g,g,
]

six = [
r,r,b,b,b,b,r,r,
r,r,b,b,b,b,r,r,
b,b,b,b,b,b,b,b,
r,r,b,b,b,b,r,r,
r,r,b,b,b,b,r,r,
b,b,b,b,b,b,b,b,
r,r,b,b,b,b,r,r,
r,r,b,b,b,b,r,r,
]

def roll_dice():
    r = random.randint(1,6)
    if r == 1:
        sense.set_pixels(one)
    elif r == 2:
        sense.set_pixels(two)
    elif r == 3:
        sense.set_pixels(three)
    elif r == 4:
        sense.set_pixels(four)
    elif r == 5:
        sense.set_pixels(five)
    elif r == 6:
        sense.set_pixels(six)

while True:
    x, y, z = sense.get_accelerometer_raw().values()

    x = abs(x)
    y = abs(y)
    z = abs(z)

    if x > 1.4 or y > 1.4 or z > 1.4:
        roll_dice()
        time.sleep(1)
This entry was posted in Raspberry Pi and tagged , , . Bookmark the permalink.

6 Responses to RaspberryPi dice project

  1. Scott Turner says:

    Thank you for this – I will have to have a go.

  2. Brittany Williams says:

    Cool project. I’m looking for an example that will be able to control the position of a LED pixel on the sense hat with the accelerometer/gyroscope.

    If the raspberry pi is rotated i want the pixel to move in the direction that it’s tilted if that makes sense.

    Having trouble finding a tutorial or example code like this. Looking for help if you can offer any!

    Thanks so much

  3. hemraj Jeetarwal says:

    Hey Great Project
    I am trying to make one ,if u cold help can u provide the circuit for this

Leave a Reply to blogmywiki Cancel reply