import time
import random
import board
import busio
import digitalio
import neopixel_spi as neopixel
import audiopwmio
from audiocore import WaveFile
NUM_PIXELS = 115
PIXEL_ORDER = neopixel.GRBW
RED = (255, 0, 0)
FLICKER_RANGE = 0.2
DELAY = 0.000000002
SOUND_FILE = "/SOUNDS/lightsaber.wav"
# Set up the SPI bus
spi = busio.SPI(clock=board.GP10, MOSI=board.GP11)
pixels = neopixel.NeoPixel_SPI(spi, NUM_PIXELS, pixel_order=PIXEL_ORDER, auto_write=False)
# Set up the button
button = digitalio.DigitalInOut(board.GP28)
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.DOWN
# Set up the audio player
audio = audiopwmio.PWMAudioOut(board.GP9)
wave = WaveFile(open(SOUND_FILE, "rb"))
# Ignition animation
def ignite_animation():
for i in range(NUM_PIXELS):
pixels[i] = RED
pixels.show()
play_sound()
# Retraction animation
def retract_animation():
for i in range(NUM_PIXELS - 1, -1, -1):
pixels[i] = (0, 0, 0)
pixels.show()
audio.stop()
# Flickering effect
def flicker_effect():
while True:
for i in range(NUM_PIXELS):
r = int(RED[0] * (1 + random.uniform(-FLICKER_RANGE, FLICKER_RANGE)))
g = int(RED[1] * (1 + random.uniform(-FLICKER_RANGE, FLICKER_RANGE)))
b = int(RED[2] * (1 + random.uniform(-FLICKER_RANGE, FLICKER_RANGE)))
pixels[i] = (r, g, b)
pixels.show()
time.sleep(DELAY)
if button.value:
retract_animation()
break
# Play sound effect
def play_sound():
print("Playing lightsaber sound...")
audio.play(wave, loop=True)
# Lightsaber activation/deactivation function
def activate_lightsaber():
ignite_animation()
flicker_effect()
# Main loop
while True:
if button.value:
activate_lightsaber()
else:
for i in range(NUM_PIXELS):
pixels[i] = (0, 0, 0)
pixels.show()
audio.stop()