In my last work, the buzzer stayed on continuously, which was not in line with the real situation, so this time I want to change the buzzer’s sounding pattern so that the buzzer’s sounding frequency is synchronised with the frequency of the LED blinking.
Main Code:
The main idea of this code is to use a boolean variable “a” to track whether the button is pressed, and the buzzer and LED will do their job accordingly.
from gpiozero import Buzzer
from gpiozero import LED
from gpiozero import Button
import threading
#initialize different component that we need to use
red = LED(4)
a = False
bz = Buzzer(16, active_high = False)
key = Button(12)
#A variable is needed to play the role of a reference, so that the computer can know when is the button pressed.
def reference():
global a
if a == False:
a = True
else:
a = False
#This function makes the LED turn on and off when the button is pressed.
def shine():
if a == True:
red.toggle()
threading.Timer(0.3,shine).start()
else:
red.off()
#This function makes the buzzer turn on and off when the button is pressed
def quick_buzz():
if a == True:
bz.toggle()
threading.Timer(0.3, quick_buzz).start()
else:
bz.off()
#This function calls the previous functions so that everything can be activated.
def start_program():
reference()
quick_buzz()
shine()
key.when_pressed = start_program
while True:
pass
What the program looks like after it runs:
Buzzer Final Project