I have raspberry pi
where I am using python to create a small buzzer script. In the script if a condition becomes True
, I need to print some information and also make buzzer sound. Buzzer sounds are made in two different format i.e. High
and Low
. In High
, I have to run below code:
GPIO.output(BUZZER, 1)
time.sleep(5)
GPIO.output(BUZZER, 0)
GPIO.cleanup()
so that buzzer make continuous sound for 5 sec. In Low
, I have to run below code:
for i in range(5):
print(i)
state = GPIO.input(BUZZER)
print("state is {}".format(state))
GPIO.output(BUZZER, 1)
time.sleep(0.3)
state = GPIO.input(BUZZER)
print("state is {}".format(state))
GPIO.output(BUZZER, 0)
time.sleep(0.3)
It will make 5 beep sounds.
Below is the python script:
def generate_sound(tempo):
if tempo == "High":
GPIO.output(BUZZER, 1)
time.sleep(5)
GPIO.output(BUZZER, 0)
GPIO.cleanup()
else:
for i in range(5):
state = GPIO.input(BUZZER)
print("state is {}".format(state))
GPIO.output(BUZZER, 1)
time.sleep(0.3)
state = GPIO.input(BUZZER)
print("state is {}".format(state))
GPIO.output(BUZZER, 0)
time.sleep(0.3)
if some_condition is True:
generate_sound("High")
print("This condition is True")
print("Here is the information you need")
print("Some more information")
else:
generate_sound("Low")
print("This condition is False")
print("Here is the information you need")
print("Some more information")
The above code is working fine but the problem is that I have to display information and generate sound at the same time. But with current approach, the sound is generated and waits for 5sec and then information is printed.
To resolve this I though of putting the generating sound function in a thread so that it can run parallel with printing information, something like below:
sound = Thread(target=generate_sound)
But here I am not sure how do I pass the values High
and Low
to generate sound function. I am not very expert in threading. Can anyone please give me some ideas. Please help. Thanks