I have used the ultrasonic sensor with Arduino successfully without any problems in the past. However, with Raspberry pi, it is not very consistent. It stops working after some time. I have have read quiet a few posts that say that its because it is getting stuck at one of the while loops (see code below). I have also tried to write a small condition to break out of the while loops, but still I am not successful. The error that I get is either t1 or t2 is referenced before it is used which means that something is not going right in the loops. Some people have also pointed out a library that can be used (https://github.com/alaudet/hcsr04sensor). So why was the same sensor running smoothly with Arduino but giving these troubles with the Pi. I can also use the library but I am really curious from programming point of view.
def cal_dist():
gp.output(trig_pin, 1)
time.sleep(0.0001)
gp.output(trig_pin, 0)
time.sleep(0.0001)
T1 = time.time()
while gp.input(echo_pin) == 0:
t1 = time.time()
if time.time() - T1 > 0.001:
print("While 1 failed")
break
T2 = time.time()
while gp.input(echo_pin) == 1:
t2 = time.time()
if t2 - T2 > 0.001:
print("While 2 failed")
break
dist = (t2-t1)*34300/2
dist = round(dist, 2)
return dist