Oct-29-2021, 04:05 PM
(This post was last modified: Oct-29-2021, 04:06 PM by deanhystad.)
Stopping turning the buzzer on does not turn it off. You need to stop the buzzer.
Why are dist and dist2 strings? You never use them as a string, so why convert a nice float to a string only to have to convert it back to a float whenever you use it? And why convert the float to an int? You never need the value as an int.
Use function arguments instead of duplicate code. distance and distance2 are the same function.
Why are dist and dist2 strings? You never use them as a string, so why convert a nice float to a string only to have to convert it back to a float whenever you use it? And why convert the float to an int? You never need the value as an int.
Use function arguments instead of duplicate code. distance and distance2 are the same function.
from time import sleep, time import RPi.GPIO as GPIO from gpiozero import PWMLED, Buzzer GPIO.setmode(GPIO.BCM) GPIO_BEEP = Buzzer(18) GPIO_TRIGGER = 23 #rx GPIO_ECHO = 24 #tx GPIO2_TRIGGER = 25 #rx GPIO2_ECHO = 8 #tx GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) GPIO.setup(GPIO2_TRIGGER, GPIO.OUT) GPIO.setup(GPIO2_ECHO, GPIO.IN) led = PWMLED(21) led2 = PWMLED(27) def distance(trigger, echo): GPIO.output(trigger, True) sleep(0.00001) GPIO.output(trigger, False) while GPIO.input(echo) == 0: pass start_time = time() while GPIO.input(echo) == 1: pass return (time() - start_time) * 17150 def ledbrightness(num): if num <= 60: brightness = 1 elif num <= 200: brightness = .1 else: brightness = 0 return brightness if __name__ == '__main__': try: while True: dist = distance(GPIO_TRIGGER, GPIO_ECHO) led.value = ledbrightness(dist) if 50 < dist < 100: speed = dist/1000 print("Speed:", speed) GPIO_BEEP.beep(speed, speed) dist2 = distance(GPIO2_TRIGGER, GPIO2_ECHO) led2.value = ledbrightness(dist2) print(dist, " : ", dist2) time.sleep(0.5) except KeyboardInterrupt: print("Measurement stopped by User") #GPIO.cleanup()Maybe the buzzer logic should be:
if dist < 100: speed = max(0.5, dist/1000) GPIO_BEEP.beep(speed, speed) else: GPIO_BEEP.off()