I'm trying to write a program that displays the output of a ultrasonic sensor attached to a Pi 3B+. The code 'hangs' by which I mean that the display of output suddenly stops and the program doesnt respond anymore. Can someone help me point out the mistake in my code?
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
TRIG = 16
ECHO = 18
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG, False)
try:
while True:
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance+1.15, 2)
if distance<=400 and distance>=5:
print "distance:",distance,"cm"
except KeyboardInterrupt:
GPIO.cleanup()
Edit: Solved the issue, the Try and except block might have been the culprit, I removed the try block and now I can output indefinitely. Thank you for you help.