import machine
import time
import random
# Define LED pins
led_pins = [6, 7, 8, 9]
# Initialize LED pins
leds = [machine.Pin(pin, machine.Pin.OUT) for pin in led_pins]
# Define button pin
button = machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_UP)
def cycle_leds():
# Cycle through LEDs in a sequence
for _ in range(3): # Repeat the cycle 3 times
for led in leds:
led.on()
time.sleep(0.1)
led.off()
def roll_die():
# Turn off all LEDs
for led in leds:
led.off()
# Generate a random number between 1 and 4
roll = random.randint(1, 4)
# Turn on the corresponding LED
leds[roll - 1].on()
print("Rolled:", roll)
def detect_button_press():
# Wait for button press
while button.value():
pass
press_start_time = time.ticks_ms()
# Wait for button release or 1 second timeout
while not button.value():
press_duration = time.ticks_diff(time.ticks_ms(), press_start_time)
if press_duration >= 1000:
cycle_leds()
roll_die()
return
# If the button was pressed and released within 1 second
roll_die()
# Main loop
while True:
detect_button_press() # Detect button press and trigger action