from machine import Pin, PWM
from time import sleep_ms
from neopixel import Neopixel
import urandom as random
import led_transform
button_down = False
button_up = False
# 設定硬體參數
LED_PIN = 13 # NeoPixel 矩陣的資料輸入腳位
MATRIX_WIDTH = 8 # 矩陣寬度
MATRIX_HEIGHT = 8 # 矩陣高度
NUM_PIXELS = MATRIX_WIDTH * MATRIX_HEIGHT # LED 總數
# 蜂鳴器接腳
buzzer = PWM(Pin(15))
def transform(index,color):
print(index)
if index <= 28:
pixels.set_pixel((led_transform.display1(index))-1, color)
elif index <= 48:
index = index - 28
pixels.set_pixel((led_transform.display2(index))-1, color)
else:
index = index - 48
pixels.set_pixel((led_transform.display3(index))-1, color)
pixels.show() # 更新 LED 顯示
sleep_ms( 50 )
pixels.fill((0, 0, 0))
pixels.show() # 更新 LED 顯示
def play_tone(frequency, duration):
buzzer.freq(frequency)
buzzer.duty_u16(30000)
sleep_ms(duration)
buzzer.duty_u16(0)
sleep_ms(50) # 音符間小停頓
# Function to handle button press interrupt (optional)
def button_press(pin):
global button_down
button_down = True
# Start Function
if __name__ == '__main__':
# Define GPIO pins for push button
button_pin = Pin(22, Pin.IN, Pin.PULL_UP) # Internal pull-up resistor
# Attach interrupt to the push button pin
button_pin.irq(trigger=Pin.IRQ_FALLING, handler=button_press)
# 初始化 NeoPixel
pixels = Neopixel(NUM_PIXELS, 0, LED_PIN, "GRB")
# 主程式
try:
while True:
if button_down == True:
for count in range(1, 61):
transform(count,(255, 0, 0))
play_tone(500, 10)
for count in range(60, 0, -1):
transform(count,(255, 0, 0))
play_tone(500, 10)
count2 = random.randint(1,60)
for count in range(1, count2):
transform(count,(255, 0, 0))
play_tone(500, 10)
for count in range(5):
transform(count2,(255, 0, 0))
play_tone(500, 100)
button_down = False
except KeyboardInterrupt:
# 清除 LED 顯示
print('清除 LED 顯示')
pixels.fill((0, 0, 0))
pixels.show() # 更新 LED 顯示