from machine import Pin, PWM
import time
# 创建 PWM 对象,连接到特定引脚(例如 GP0)
speaker = PWM(Pin(0))
# 设置频率和占空比
speaker.freq(1000) # 1kHz 频率
speaker.duty_u16(32768) # 50% 占空比
def play_tone(frequency, duration):
speaker = PWM(Pin(0))
speaker.freq(frequency)
speaker.duty_u16(32768)
time.sleep(duration)
speaker.duty_u16(0) # 停止声音
# 播放音阶
# play_tone(262, 0.5) # 中音 Do
# play_tone(294, 0.5) # 中音 Re
# play_tone(330, 0.5) # 中音 Mi
# 定义音符频率
NOTES = {
'C4': 262,
'D4': 294,
'E4': 330,
'F4': 349,
'G4': 392,
'A4': 440,
'B4': 494
}
def play_melody(melody, durations):
speaker = PWM(Pin(0))
for note, duration in zip(melody, durations):
if note in NOTES:
speaker.freq(NOTES[note])
speaker.duty_u16(32768)
time.sleep(duration)
speaker.duty_u16(0)
time.sleep(0.1) # 音符间短暂停顿
# 播放小星星
melody = ['C4', 'C4', 'G4', 'G4', 'A4', 'A4', 'G4']
durations = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1.0]
while True:
play_melody(melody, durations)