首先来一个简单的,变频率的蜂鸣器,声音会越来越尖锐。直接上程序吧,
import machine
from machine import Pin
import time
led = Pin("LED",Pin.OUT)
buzze = machine.Pin(26)
pwm1 = machine.PWM(buzze)
frep1 = 100
pwm1.freq(frep1)
pwm1.duty_u16(32768)
while True:
led.value(1)
frep1 += 100
pwm1.freq(frep1)
time.sleep(.25)
led.value(0)
time.sleep(.25)
if frep1 > 2400:
frep1 = 200
实验二,根据不同的频率对应音乐的不同音调,在其他网友的基础上改的一个《生日歌》
生日快乐歌的简谱见下图,我也不懂音律就不做解析了,按照上面的谱进行设置。
测试代码见下。
from machine import Pin, PWM
from time import sleep
buzzer = PWM(Pin(20))
vol = 1300 #音量大小
def DO(time):
buzzer.freq(1046) #1
buzzer.duty_u16(vol)
sleep(time)
def RE(time):
buzzer.freq(1175) #2
buzzer.duty_u16(vol)
sleep(time)
def MI(time):
buzzer.freq(1318) #3
buzzer.duty_u16(vol)
sleep(time)
def FA(time):
buzzer.freq(1397) #4
buzzer.duty_u16(vol)
sleep(time)
def SO(time):
buzzer.freq(1568) #5
buzzer.duty_u16(vol)
sleep(time)
def LA(time):
buzzer.freq(1760) #6
buzzer.duty_u16(vol)
sleep(time)
def SI(time):
buzzer.freq(1967) #7
buzzer.duty_u16(vol)
sleep(time)
def N(time):
buzzer.duty_u16(0) #close
sleep(time)
while True:
SO(0.17) #5
N(0.01) #0
SO(0.17) #5
LA(0.33) #6
SO(0.33) #5
DO(0.33) #1
N(0.01) #0
SI(0.33) #7-
N(0.01) #0
SI(0.33) #7-
SO(0.33) #5
LA(0.33) #6
SO(0.33) #5
RE(0.33) #2
N(0.01) #0
DO(0.33) #1
N(0.01) #0
DO(0.33) #1
SO(0.33) #5
SO(0.33) #5
MI(0.33) #3
DO(0.33) #1
N(0.01) #0
DO(0.33) #1
SI(0.33) #7-
LA(0.33) #6
N(0.01) #0
LA(0.33) #6
N(0.01) #0
FA(0.33) #4
N(0.01) #0
FA(0.33) #4
MI(0.33) #3
RE(0.33) #2
DO(0.33) #1
N(0.01) #0
DO(0.33) #1
N(0.67) #0