import time
import random
import digitalio
import board
import neopixel
import audiopwmio
from audiocore import WaveFile
# Define the sound file paths
lightsaber_sound = "/SOUNDS/lightsaber.wav"
# Initialize the Neopixel strip
pixel_pin = board.GP0
num_pixels = 114
pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.05, pixel_order=neopixel.GRBW)
# Initialize the button
button = digitalio.DigitalInOut(board.GP28)
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.DOWN
# Initialize the audio player
speaker = audiopwmio.PWMAudioOut(board.GP9)
is_on = False
button_state = False
start_time = time.monotonic()
# Function to fill the pixels with a flickering effect
def fill_pixels_with_flicker(color, speed):
for i in range(num_pixels):
flicker = random.randint(-50, 50)
pixel_color = (max(0, min(255, color[0] + flicker)),
max(0, min(255, color[1] + flicker)),
max(0, min(255, color[2] + flicker)))
pixels[i] = pixel_color
time.sleep(speed / num_pixels)
while True:
if button.value and not button_state:
is_on = not is_on
button_state = True
if is_on:
# Instant ignition
for i in range(num_pixels):
pixels[i] = (255, 0, 0, 0)
pixels.show()
# Play the lightsaber sound
with open(lightsaber_sound, "rb") as f:
wave = WaveFile(f)
speaker.play(wave, loop=True)
else:
# Instant retraction
for i in range(num_pixels-1, -1, -1):
pixels[i] = (0, 0, 0, 0)
pixels.show()
time.sleep(0.001)
# Stop the lightsaber sound
speaker.stop()
if not button.value:
button_state = False