23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
else :
stopAlertor()
print ('buzzer off ...')
def alertor():
p. start(50)
for x in range(0,361): #frequency of the alarm along the sine wave change
sinVal = math.sin(x * (math.pi / 180.0)) #calculate the sine value
toneVal = 2000 + sinVal * 500 #Add to the resonant frequency with a Weighted
p. ChangeFrequency(toneVal) #output PWM
time.sleep(0.001)
def stopAlertor():
p. stop()
def destroy():
GPIO. output(buzzerPin, GPIO. LOW) # buzzer off
GPIO. cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
e xcept KeyboardInterrupt: # When 'Ctrl+C' is pressed, the subprogram destroy() will
be executed.
destroy()
The code is the same to the active buzzer logically, but the way to control the buzzer is different. Passive
buzzer requires PWM of certain frequency to control, so you need to create a software PWM pin through
softToneCreate (buzzeRPin). The way to create PWM is also introduced before in the sections about
BreathingLED and RGBLED.
def setup():
g lobal p
p rint ('Program is starting...')
GPIO. setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO. setup(buzzeRPin, GPIO.OUT) # Set buzzeRPin's mode is output
GPIO. setup(buttonPin, GPIO. IN, pull_up_down=GPIO.PUD_UP) # Set buttonPin's mode is
input, and pull up to high level(3.3V)
p = GPIO. PWM(buzzeRPin, 1)
p. start(0);