我有一个Raspberry pi皮科和一个蜂鸣器,我将其连接到GPIO 15。我可以使用MicroPython和Thony让它发出嗡嗡声并播放几个音符,如下所示:
from machine import Pin, PWM
from utime import sleep
buzzer = PWM(Pin(15))
tones = {
"C5": 523,
"CS5": 554,
"D5": 587,
"DS5": 622,
"E5": 659,
"F5": 698,
"FS5": 740,
"G5": 784,
"GS5": 831,
"A5": 880,
"AS5": 932,
"B5": 988,
}
song = ["E5","G5","A5","P","E5","G5","B5","A5","P","E5","G5","A5","P","G5","E5"]
led = Pin(25, Pin.OUT)
def playtone(frequency):
buzzer.duty_u16(1000)
buzzer.freq(frequency)
led.toggle()
def bequiet():
buzzer.duty_u16(0)
def playsong(mysong):
for i in range(len(mysong)):
if (mysong[i] == "P"):
bequiet()
else:
playtone(tones[mysong[i]])
sleep(0.3)
bequiet()
playsong(song)
它的工作原理就像一个魔咒。然而,我不是一个python的人,我想用C/Rust做同样的事情。我已经做了几天的研究,现在认为我应该用PWM来做,但我非常不知所措。请帮助。
1条答案
按热度按时间j13ufse21#
WiringPi是一个相当成熟的C语言中的RPi GPIO访问库。
它还附带了像PWM和tones这样的东西,应该会很有帮助。
下面是一个如何使用它的示例: