from machine import Pin, I2C, PWM, RTC
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)
# RTC 內建時鐘
rtc = RTC()
# 設定一次時間 (年, 月, 日, 星期, 時, 分, 秒, 子秒)
# 記得自己修改
rtc.datetime((2025, 12, 22, 0, 12, 30, 0, 0))
# 蜂鳴器 PWM
buzzer = PWM(Pin(15))
buzzer.duty_u16(0)
# LED
led = Pin(14, Pin.OUT)
led.off()
# 音階
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)
]
# Songs (同前略)...
# ---------------- 省略歌曲資料 ----------------
def get_time_string():
y, m, d, wd, hh, mm, ss, sub = rtc.datetime()
return "{:02d}:{:02d}:{:02d}".format(hh, mm, ss)
def play_note(note, duration):
if note == "REST":
buzzer.duty_u16(0)
led.off()
else:
buzzer.freq(NOTE[note])
buzzer.duty_u16(30000)
led.on()
time.sleep(duration)
buzzer.duty_u16(0)
led.off()
time.sleep(0.05)
def draw_tree(lights=True):
oled.fill(0)
# 顯示時間
oled.text(get_time_string(), 32, 0, 1)
cx = 64 # 標準 OLED 的中心
top = 12 # 樹最上端位置
# 三角形高度
h1 = 12 # 第一層
h2 = 15 # 第二層
h3 = 18 # 第三層
# ★ 第一層(最小)
for i in range(h1):
oled.line(cx - i, top + i, cx + i, top + i, 1)
# ★ 第二層
base2 = top + h1 - 3
for i in range(h2):
oled.line(cx - (i + 6), base2 + i, cx + (i + 6), base2 + i, 1)
# ★ 第三層(最大)
base3 = base2 + h2 - 5
for i in range(h3):
oled.line(cx - (i + 12), base3 + i, cx + (i + 12), base3 + i, 1)
# 樹幹
trunk_top = base3 + h3
oled.fill_rect(cx - 5, trunk_top, 10, 12, 1)
# 星星
oled.text("*", cx - 2, top - 8, 1)
# 聖誕燈
if lights:
for _ in range(20):
x = random.randint(cx - 22, cx + 22)
y = random.randint(top + 10, trunk_top - 4)
oled.pixel(x, y, 1)
oled.show()
def play_song(song, title):
for note, dur in song:
draw_tree(True)
play_note(note, dur)
draw_tree(False)
time.sleep(1)
# 主迴圈
while True:
play_song(JINGLE_BELLS, "JB")
time.sleep(1)
play_song(WE_WISH, "WW")
time.sleep(1)
Loading
ssd1306
ssd1306