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)   
    gp.output(trig_pin, 0)

    T1 = time.time()

    while gp.input(echo_pin) == 0:
        t1 = time.time()

        if time.time() - T1 > 0.001:
            print("While 1 failed")

    T2 = time.time()

    while gp.input(echo_pin) == 1:     
        t2 = time.time()

        if t2 - T2 > 0.001:
            print("While 2 failed")

    dist = (t2-t1)*34300/2

    dist = round(dist, 2)

    return dist

1 Answer 1


The code you use has the standard errors for this algorithm. It assumes everything always works perfectly without error.

As a programming exercise you need to think about under what conditions the while loops would not terminate. You then need to protect against those conditions. The code you linked has added protection in one loop but not the other. It may still fail in the other loop but such a failure will be fairly rare.

Arduino scripts are written in the knowledge that only one program is running at a time and the script will not be preempted.

Linux scripts must be written in the knowledge that many programs will be running at the same time and the script is quite likely to be preempted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.