this is the simple code to measure distance using ultrasoinic sensor attached to reapberry-pi and by writing python script--

import RPi.GPIO as GPIO

import time


TRIG = 16

ECHO = 20

print "Distance Measurement In Progress"



while True:

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"

use case is- I have to run this script only when all the pins of ultrasonic sensor is properly connected to the circuit and the raspberry-pi. so my question is, can we identify the pin connection before running the script? or can we identify whether our hardware is working properly or not?


Send a trigger. If you do not get a response within a timeout period assume the device isn't present.

  • can u plz tell me how to send external trigger in raspberry-pi using python. – andy Dec 13 '16 at 11:14
  • @andy I would send the trigger in the same way as the code does at the moment. – joan Dec 13 '16 at 11:49

To the best of my knowledge, unless you use an EEPROM chip (like Pi HATs HAT specification) then you will be able to know what GPIO pins need to be setup, otherwise it's anyone's guess; unless you want to flat out ask the user in the code what pins they have configured (or get that information from command line arguments) i.e. add the following to your code:


TRIG = int(raw_input('What pin are you using for the trigger?  '))
ECHO = int(raw_input('What pin are you using for the echo?  '))


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.