from machine import Pin, PWM
import time
# 设置蜂鸣器引脚和PWM对象
buzzer_pin = Pin(25)
buzzer_pwm = PWM(buzzer_pin)
#按键
LED=Pin(2,Pin.OUT) #构建LED对象,开始熄灭
KEY=Pin(0,Pin.IN,Pin.PULL_UP) #构建KEY对象
state=0 #LED引脚状态
music_playing = True # 控制音乐是否正在播放
# LED状态翻转函数
def toggle_LED(KEY):
global state, music_playing
time.sleep_ms(10) # 消除抖动
if KEY.value() == 0: # 确认按键被按下
state = not state
LED.value(state)
if not state: # 如果按键按下时LED亮起(state为假),则切换音乐播放状态
music_playing = not music_playing
# 定义中断,下降沿触发
KEY.irq(toggle_LED, Pin.IRQ_FALLING)
# 定义音符频率
notes = {
'C4': 262, #1
'D4': 294, #2
'E4': 330, #3
'F4': 349, #4
'G4': 392, #5
'A4': 440, #6
'B4': 494, #7
'C5': 523, #8
'SC4': 524, #1
'SD4': 588, #2
'SE4': 660, #3
'SF4': 698, #4
'SG4': 784, #5
'SA4': 880, #6
'SB4': 988, #7
'SC5': 1046 #8
}
# 定义沧海一声笑的音符和持续时间
melody = [
('SA4', 600), ('SG4', 300), ('SE4', 300), ('SD4', 300),('SC4', 1000),
('SE4', 600), ('SD4', 300), ('SC4', 300),('A4', 300), ('G4', 1000),
('G4', 600), ('A4', 300),('G4', 600), ('A4', 300), ('C4', 500), ('SD4', 500),('SE4', 500), ('SG4', 500),
('SA4', 500), ('SG4', 500),('SE4', 500), ('SD4', 250), ('SC4', 500), ('SD4', 1000),
('SA4', 500), ('SA4', 250),('SG4', 250), ('SE4', 500),('SD4', 500), ('SC4', 1000),
('SE4', 600), ('SD4', 500),('SC4', 500), ('A4', 500),('G4', 1000),
('G4', 600), ('A4', 500),('G4', 600), ('A4', 500),('SC4', 600), ('SD4', 500),('SE4', 500), ('SG4', 500),
('SA4', 600), ('SG4', 250), ('SE4', 250),('SD4', 250), ('SC4', 500), ('SD4', 1000),
('SA4', 500), ('SA4', 250),('SG4', 250), ('SE4', 300), ('SD4', 300),('SC4', 1000),
('SE4', 600),('SD4', 250), ('SC4', 300),('A4', 300), ('G4', 1000),
('G4', 600), ('A4', 500),
('G4', 600), ('A4', 500),('SC4', 600), ('SD4', 300),('SE4', 300), ('SG4', 300),
('SA4', 600),('SG4', 300), ('SE4', 250),('SD4', 250), ('SC4', 300),('SD4', 1000),
('SA4', 500), ('SA4', 250),('SG4', 250), ('SE4', 300),('SD4', 300), ('SC4', 1000),
('SE4', 600), ('SD4', 250),('SC4', 300), ('A4', 300),('G4', 1000),
('G4', 600),('A4', 300), ('G4', 600),('A4', 300), ('SC4', 600),('SD4', 250), ('SE4', 300),('SG4', 300),
('SA4', 600), ('SG4', 300),('SE4', 300), ('SD4', 300),('SC4', 1000)
]
# 播放音乐函数
def play_music():
for note, duration in melody:
if music_playing: # 判断音乐是否正在播放
buzzer_pwm.freq(notes[note])
buzzer_pwm.duty(512) # 设置占空比为50%(中等音量)
time.sleep_ms(duration)
buzzer_pwm.duty(0) # 停止发声
time.sleep_ms(50) # 短暂的间隔
# 循环播放音乐
while True:
play_music()