Hey, I’m new and not really an expert at coding with Python so I need some help with using while loops for my school project. Currently, I have a buzzer that will be triggered and beeps forever when a vibration switch registers a vibration. I have a button that will stop the beeping of the buzzer. However, the next time the vibration switch does record a vibration, the buzzer will only beep once instead of always beeping. What should I do to make the buzzer always beep every time the vibration switch is triggered? Here is my code:
import RPi.GPIO as GPIO
import time
buzzer = 15 # Original is 11 (GPIO17), we use 15 (GPIO22)
BtnPin = 16
VibratePin = 11
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(BtnPin, GPIO.IN, pull_up_down = GPIO.PUD_UP) #Button
GPIO.setup(buzzer, GPIO.OUT)
GPIO.setup(VibratePin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
b=0 #Define b
def beep(x): #Configure how the beeping works
on()
time.sleep(x)
off()
time.sleep(x)
def on():
GPIO.output(buzzer, GPIO.LOW)
def off():
GPIO.output(buzzer, GPIO.HIGH)
while True:
loop_beep = True
state = 0
#GPIO.output(buzzer, GPIO.HIGH) #Buzzer is OFF
if GPIO.input(VibratePin)==0: #Vibration Switch triggered
print("Triggered")
while loop_beep: # Beep forever till button is pressed
beep(0.5)
button_state = GPIO.input(16)
if button_state == 0:
if b == 1:
b = 0
else:
b = 1
if b == 1: #When button is pressed
print("Pressed button")
loop_beep = False
state = state + 1
if state > 1:
state = 0
loop_beep = True
else:
print("Running")