#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
Buzzer = 11 # pin11
def setup(pin):
global BuzzerPin
BuzzerPin = pin
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(BuzzerPin, GPIO.OUT)
GPIO.output(BuzzerPin, GPIO.HIGH)
def on():
GPIO.output(BuzzerPin, GPIO.LOW)
def off():
GPIO.output(BuzzerPin, GPIO.HIGH)
def beep(x):
on()
time.sleep(x)
off()
time.sleep(x)
def loop():
while True:
beep(1)
def destroy():
GPIO.output(BuzzerPin, GPIO.HIGH)
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup(Buzzer)
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()
2. 无源蜂鸣器
内部没有振荡源,使用直流信号不会发出蜂鸣声,需要使用频率在2k到5k间的方波驱动它。
《九九艳阳天》简谱
https://www.zhaogepu.com/jianpu/3422.html
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
Buzzer = 11
CL = [0, 131, 147, 165, 175, 196, 211, 248] # Frequency of Low C notes
CM = [0, 262, 294, 330, 350, 393, 441, 495] # Frequency of Middle C notes
CH = [0, 525, 589, 661, 700, 786, 882, 990] # Frequency of High C notes
song_3 = [ 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_3 = [
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, 1, 2, 1, 8,
]
def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(Buzzer, GPIO.OUT) # Set pins' mode is output
global Buzz # Assign a global variable to replace GPIO.PWM
Buzz = GPIO.PWM(Buzzer, 440) # 440 is initial frequency.
Buzz.start(50) # Start Buzzer pin with 50% duty ration
def loop():
while True:
print('\n Playing song 3...')
for i in range(1, len(song_3)): # Play song 1
Buzz.ChangeFrequency(song_3[i]) # Change the frequency along the song note
time.sleep(beat_3[i] * 0.2) # delay a note for beat * 0.2s
def destory():
Buzz.stop() # Stop the buzzer
GPIO.output(Buzzer, 1) # Set Buzzer pin to High
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destory()