#LED Dice project for MICROBIT - by JONATHAN DAVIES
#copyright 2017 iwasp.eu
from microbit import *
import random
port = [pin0,pin1,pin8,pin16,pin12,pin2,pin14] #List of GPIO pins to use
def outputDice(disp,roll): #Function to display rolled number on the screen and LED array
for n in range(7): # Turn off all GPIO pins and LEDs
port[n].write_digital(0)
for n in range(7): #Check values in dice array and where value is '1', turn on corresponding LED.
if (disp[n]==1):
port[n].write_digital(1)
display.show(str(roll)) #dislay on screen
def randomFlash(): #Function togenerate random LED flashing, mimicking dice rolling action
for n in range(7): # Turn off all GPIO pins and LEDs
port[n].write_digital(0)
light=[] #list to hold which LEDs to be randomly on.
for pop in range(0,15): #populate array with 16 random dice numbers 1-6
light.append(random.randrange(1,7)) #add a random dice LED number into the array
for n in range(0,15): #Flash 16 random dice lights
port[light[n]].write_digital(1) #turn on LED corresponding to next entry in 'light' list
sleep(75) #do nothing, keeps LED on for 0.075 seconds
port[light[n]].write_digital(0) #turn off LED
rollagain = "y"
while (rollagain == "y"): #main loop continues to generate dice roll until user ends
diceRoll = random.randrange(1,7) #generate random roll value
#create LED dice list dependant on roll value
if (diceRoll == 1):
dice = [0,0,0,1,0,0,0]
elif(diceRoll == 2):
dice = [1,0,0,0,0,0,1]
elif(diceRoll == 3):
dice = [0,0,1,1,1,0,0]
elif(diceRoll == 4):
dice = [1,0,1,0,1,0,1]
elif(diceRoll == 5):
dice = [1,0,1,1,1,0,1]
elif(diceRoll == 6):
dice = [1,1,1,0,1,1,1]
# dice list item places
# 0 1 2
# 3
# 4 5 6
# dice microbit pin numbers
# 0 1 8
# 16
# 12 2 14
randomFlash() #call function to mimic dice roll with random LED flashes
outputDice(dice,diceRoll) #call function with dice list and roll value to display
#the dice value on screen and on LED array
rollagain = "n"
# wait for button A or B to be pressed before continuing to next roll
while (rollagain == "n"):
if (button_a.is_pressed() or button_b.is_pressed()):
rollagain = "y"
#end of main loop
Comments
Please log in or sign up to comment.