from machine import Pin,PWM
import time
pwm0 = PWM(Pin(22))#連接蜂鳴器正極
tone = [784,880,988,1046,1175,1318,1387,1568]
#       中5  中6 中7  高1  高2  高3  高4  高5 
#        0     1   2    3    4    5    6   7
music = [#簡譜上對應的音階列表
5,5,5,6,7,5,4,4,
3,3,3,4,5,5,2,2,
1,5,4,1,5,4,
1,5,4,3,3,
5,5,5,6,7,5,4,4,
3,3,3,4,5,5,2,2,
1,5,4,1,5,4,
1,5,4,3,3,
5,4,7,6,5,5,4,4,
7,6,5,6,7,5,4,
3,1,5,4,3,0,5,4,4,
6,5,6,5,3,
6,5,6,5,3,4,3
]
times = [#每个音階對應的拍數
8,4,4,8,8,12,4,8,8,
8,4,4,8,8,12,4,8,8,
8,8,8,8,
8,8,8,8,
8,8,12,4,8,8,8,8,
8,4,4,8,8,12,4,8,8,
8,4,4,8,8,12,4,8,8,
8,8,8,8,
8,8,8,8,
8,8,12,4,8,8,8,4,4,
8,8,8,4,4,4,4,8,8,4,4,
8,4,12,8,8,8,8,4,
8,12,4,8,4,4,8,8,
4,4,4,4,8,8,
4,4,4,4,12,4,8,8,8,8,]
i = 0
while True:
  q = times[i]/12#取出這一音階所占的音拍
  w = tone[music[i]]#取出該音调
  pwm0.init(freq=w)#重置PWM输出,設置PWM的输出频率讓蜂鳴器發音
  time.sleep(q)#設置蜂鳴器的音拍,也就是讓它發出多久的音
  print(w)#輸出该發音頻率
  i=i+1#指向下一個音
  if i>len(music)-1:#當music列表裏的音都結束了此首歌也播放完畢
     pwm0.deinit()#關閉PWM输出
     break