# https://chatgpt.com/share/693e948a-bfa8-8004-9146-97f331e84514
from machine import Pin, I2C, PWM
import ssd1306
import time
import random
# OLED I2C
i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# 蜂鳴器 PWM
buzzer = PWM(Pin(15))
buzzer.duty_u16(0)
# 音階
NOTE = {
"C4": 262, "D4": 294, "E4": 330, "F4": 349,
"G4": 392, "A4": 440, "B4": 494,
"C5": 523, "D5": 587, "E5": 659,
"REST": 0
}
# Jingle Bells
JINGLE_BELLS = [
("E4", 0.4), ("E4", 0.4), ("E4", 0.8),
("E4", 0.4), ("E4", 0.4), ("E4", 0.8),
("E4", 0.4), ("G4", 0.4), ("C4", 0.4),
("D4", 0.4), ("E4", 1.2),
("F4", 0.4), ("F4", 0.4), ("F4", 0.4),
("F4", 0.4), ("F4", 0.4), ("E4", 0.4),
("E4", 0.4), ("E4", 0.4),
("E4", 0.4), ("D4", 0.4),
("D4", 0.4), ("E4", 0.4),
("D4", 0.8), ("G4", 0.8)
]
# We Wish You a Merry Christmas
WE_WISH = [
("G4", 0.4), ("C5", 0.8),
("C5", 0.4), ("D5", 0.4), ("C5", 0.4), ("B4", 0.8),
("A4", 0.4), ("A4", 0.4), ("D5", 0.8),
("D5", 0.4), ("E5", 0.4), ("D5", 0.4), ("C5", 0.8),
("B4", 0.4), ("G4", 0.4),
("G4", 0.4), ("E4", 0.4), ("C4", 0.8),
("A4", 0.8), ("D5", 0.8)
]
# 播放音符
def play_note(note, duration):
if note == "REST":
buzzer.duty_u16(0)
else:
buzzer.freq(NOTE[note])
buzzer.duty_u16(30000)
time.sleep(duration)
buzzer.duty_u16(0)
time.sleep(0.05)
# 播放歌曲
def play_song(song, title):
for note, dur in song:
draw_tree(True)
play_note(note, dur)
draw_tree(False)
show_message(title)
# 畫聖誕樹
def draw_tree(lights=True):
oled.fill(0)
cx = 64
top = 8
h = 40
for i in range(h):
oled.line(cx - i, top + i, cx + i, top + i, 1)
oled.fill_rect(cx - 4, top + h, 8, 10, 1)
oled.text("*", cx - 2, top - 6, 1)
if lights:
for _ in range(12):
x = random.randint(cx - h, cx + h)
y = random.randint(top + 5, top + h - 5)
oled.pixel(x, y, 1)
oled.show()
# 顯示文字
def show_message(text):
oled.fill(0)
oled.text(text, 0, 28, 1)
oled.show()
time.sleep(2)
# 主迴圈
while True:
play_song(JINGLE_BELLS, "Jingle Bells")
time.sleep(1)
play_song(WE_WISH, "We Wish You")
time.sleep(2)