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.
The error was with the Try and Except block of the code, if the receiver on the board doesnt receiver any echo output, it fails the try block and enters the except block where I clear all the pins attached to the Pi. This is why the code stops working after a while, the pins get cleared as soon as an Echo is not detected. removing the try block allows for uninterrupted ranging. Code should be modified as below:
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)
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"