Mini Project: Electronic Die

Objective

You are going to light one of the six LEDs randomly to mimic the throw of a die. Your program will choose a random number between 1 and 6, then light the corresponding LED for a period of time.

Components

  • 1 Metro M0 Express

  • 1 breadboard

  • 6 LEDs of any color

  • 1 resistor (330 ohm)

  • Wires

Wiring

We are going to be using the same circuit as we did in the LED Array exercise. The diagram is provided again here for reference.

Remember the shorter leg (negative side -- cathode) of the LED goes to the GND, and the longer leg (positive side -- anode) goes to a pin. Follow the circuit diagram provided below to wire the Metro M0 Express.

Coding/Programming

import board

import digitalio

import time

import random


L0 = digitalio.DigitalInOut(__________)

L1 = digitalio.DigitalInOut(__________)

L2 = digitalio.DigitalInOut(__________)

L3 = digitalio.DigitalInOut(__________)

L4 = digitalio.DigitalInOut(__________)

L5 = digitalio.DigitalInOut(__________)


leds = [L0, L1, L2, L3, L4, L5] # list of LEDs


for i in leds:

i.direction = digitalio.Direction.__________ # define the direction of the digital pin


while True:

x = random.randint(0, 5) # random index, corresponding to an element in leds

leds[__________].value = __________ # turn LED on

time.sleep(1) # delay

leds[__________].value = __________ # turn LED off

time.sleep(1)

Solution

import board

import digitalio

import time

import random

L0 = digitalio.DigitalInOut(board.D7)

L1 = digitalio.DigitalInOut(board.D6)

L2 = digitalio.DigitalInOut(board.D5)

L3 = digitalio.DigitalInOut(board.D4)

L4 = digitalio.DigitalInOut(board.D3)

L5 = digitalio.DigitalInOut(board.D2)

leds = [L0, L1, L2, L3, L4, L5] # list of LEDs

for i in leds:

i.direction = digitalio.Direction.OUTPUT # define the direction of the digital pin

# in this case, the direction is set to OUTPUT: writing digital data out

while True:

x = random.randint(0, 5) # random index, corresponding to an element in leds

leds[x].value = True # turn LED on

time.sleep(1) # delay

leds[x].value = False # turn LED off

time.sleep(1)