I took a piece of code from the internet in order to use my ultrasonic sensor. But I don't fully understand it. I understand that the lines:

GPIO.output(TRIG, True)
GPIO.output(TRIG, False

keeps the bip for 0.00001 seconds, then the pulse_start it the timestamp when the sensor starts receiving the echo and pulse_end is the timestamp when the sensor finishes receiving the echo.

Shoudn't the pulse_start be the timestamp when the beep ended, and pulse_end be the timestamp when echo receiving ended?

import RPi.GPIO as GPIO
import time

TRIG = 23 
ECHO = 24

print "Distance Measurement In Progress"


GPIO.output(TRIG, False)
print "Waiting For Sensor To Settle"

GPIO.output(TRIG, True)
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, 2)

print "Distance:",distance,"cm"


Thank you!

2 Answers 2


I can't find any definitive information.

My own experience is that timing the length of the echo gives correct measurements. Timing from the end of the trigger would introduce a fixed error of about 7 centimetres. Of course as the error is fixed it could be removed from all results, however the offset might vary between acoustic rangers.

Sonar ranger trigger and echo

The trace above shows the 10 µs trigger pulse on GPIO 5. GPIO 12 is connected to the echo output. On my sonar the echo line goes high 430 µs after the trigger. In the example shown it goes low again in 4725 µs for a range of 80.4 cms.

By the way, the code you copied contains several errors which I' sure you will discover in the fullness of time.

  • If you find errors, please signal them here. Feb 27, 2016 at 12:49
  • I've pointed out the errors in that code more times than I care to remember. I really can't be bothered to do so yet again.
    – joan
    Feb 27, 2016 at 13:03

Does it work now ?

If I understand your question, I would suggest the first while loop.

while GPIO.input(ECHO)==0:
  pulse_start = time.time()

is waiting and ensuring that the code does not confuse the "pulse" as the return echo. When you yell in a canyon you want to ignore the first sound since it is your own voice, not the voice that returns after bouncing off the distant wall and returns.

If you want to test this theory, add one more time stamp before the code

GPIO.output(TRIG, False)
test_time = time.time()  #  add this new time stamp
while GPIO.input(ECHO)==0:
  pulse_start = time.time()

and then print out all three time stamps. test.time and pulse_start may be very close together. You can even calculate the distance for these two times.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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