蜂鸣器分为有源和无源两种,这次的 MH-FMD 是无源蜂鸣器, 也就是需要通过 PWM 更改频率实现对蜂鸣器的控制.

关于 PWM 可以参考这篇文章MicroPython-ESP32 PWM

代码分为三部分,第一部分导包和创建 PWM 对象:

1
2
from machine import Pin,PWM
buzzer = PWM(Pin(12, Pin.OUT), freq=440, duty=56)

第二部分为各个音符的频率和歌曲对应的音符和节奏:

1
2
3
4
5
6
7
8
9
10
11
12
13
CL = [0, 131, 147, 165, 175, 196, 211, 248]
CM = [0, 262, 294, 330, 350, 393, 441, 495]
CH = [0, 525, 589, 661, 700, 786, 882, 990]

song = [CM[5], CM[5], CM[6], CH[1], CM[6], CM[5], CM[3], CM[2], CM[5], CM[6], CH[1], CH[1], CM[6], CH[1], CH[2], CH[3], CH[2],
CH[1], CH[2], CH[3], CH[5], CH[3], CH[2], CH[3], CH[1], CH[3], CH[2], CH[2], CH[1], CM[6], CM[5], CM[6], CM[5], CM[3],
CM[2], CM[3], CM[2], CM[3], CM[5], CM[5], CM[6], CM[5], CM[2], CH[3], CH[1], CH[2], CM[6], CM[5], CM[3], CM[5], CM[3],CM[2], CM[3],
CH[3], CH[3], CH[2], CH[1], CH[2], CH[3], CH[5], CH[2], CH[2], CH[3], CM[7], CM[6], CM[7], CM[6], CM[7], CM[5], CM[6], CH[1]]

beat = [2, 4, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 2, 4,
1, 1, 4, 1, 1, 1, 1, 4, 2, 2, 1, 1, 1, 1, 2, 4, 2,
1, 1, 4, 2, 2, 4, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4,
2, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 1, 2, 1, 8, 1]

第三部分为循环歌曲的音符实现播放歌曲:

1
2
3
for i in range(len(song)):
buzzer.freq(song[i])
time.sleep(beat[i] * 0.2)

完整的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from machine import Pin,PWM

buzzer = PWM(Pin(12, Pin.OUT), freq=440, duty=56)

CL = [0, 131, 147, 165, 175, 196, 211, 248]
CM = [0, 262, 294, 330, 350, 393, 441, 495]
CH = [0, 525, 589, 661, 700, 786, 882, 990]

song = [CM[5], CM[5], CM[6], CH[1], CM[6], CM[5], CM[3], CM[2], CM[5], CM[6], CH[1], CH[1], CM[6], CH[1], CH[2], CH[3], CH[2],
CH[1], CH[2], CH[3], CH[5], CH[3], CH[2], CH[3], CH[1], CH[3], CH[2], CH[2], CH[1], CM[6], CM[5], CM[6], CM[5], CM[3],
CM[2], CM[3], CM[2], CM[3], CM[5], CM[5], CM[6], CM[5], CM[2], CH[3], CH[1], CH[2], CM[6], CM[5], CM[3], CM[5], CM[3],CM[2], CM[3],
CH[3], CH[3], CH[2], CH[1], CH[2], CH[3], CH[5], CH[2], CH[2], CH[3], CM[7], CM[6], CM[7], CM[6], CM[7], CM[5], CM[6], CH[1]]

beat = [2, 4, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 2, 4,
1, 1, 4, 1, 1, 1, 1, 4, 2, 2, 1, 1, 1, 1, 2, 4, 2,
1, 1, 4, 2, 2, 4, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4,
2, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 1, 2, 1, 8, 1]

while True:
for i in range(len(song)):
buzzer.freq(song[i])
time.sleep(beat[i] * 0.2)