Things used in this project

Hardware components:
Pi 3 02
Raspberry Pi 3 Model B
08377 02 l
Resistor 330 ohm
Mfr 25fbf52 475r sml
Resistor 475 ohm
12002 04
Breadboard (generic)
11026 02
Jumper wires (generic)
51gzz5eu9pl. sx425
Ultrasonic Sensor - HC-SR04 (Generic)


Connection Diagram
Interfacing raspberry pi with hc sr04 circuit diagram 600x361 napzhquagj


import RPi.GPIO as GPIO                    #Import GPIO library
import time                                #Import time library
GPIO.setmode(GPIO.BCM)                     #Set GPIO pin numbering 

TRIG = 23                                  #Associate pin 23 to TRIG
ECHO = 24                                  #Associate pin 24 to ECHO

print "Distance measurement in progress"

GPIO.setup(TRIG,GPIO.OUT)                  #Set pin as GPIO out
GPIO.setup(ECHO,GPIO.IN)                   #Set pin as GPIO in

while True:

  GPIO.output(TRIG, False)                 #Set TRIG as LOW
  print "Waitng For Sensor To Settle"
  time.sleep(2)                            #Delay of 2 seconds

  GPIO.output(TRIG, True)                  #Set TRIG as HIGH
  time.sleep(0.00001)                      #Delay of 0.00001 seconds
  GPIO.output(TRIG, False)                 #Set TRIG as LOW

  while GPIO.input(ECHO)==0:               #Check whether the ECHO is LOW
    pulse_start = time.time()              #Saves the last known time of LOW pulse

  while GPIO.input(ECHO)==1:               #Check whether the ECHO is HIGH
    pulse_end = time.time()                #Saves the last known time of HIGH pulse 

  pulse_duration = pulse_end - pulse_start #Get pulse duration to a variable

  distance = pulse_duration * 17150        #Multiply pulse duration by 17150 to get distance
  distance = round(distance, 2)            #Round to two decimal points

  if distance > 2 and distance < 400:      #Check whether the distance is within range
    print "Distance:",distance - 0.5,"cm"  #Print distance with 0.5 cm calibration
    print "Out Of Range"                   #display out of range


Arbaz Hussain
0 projects • 8 followers
cat /etc/arbaz | grep Machine Learning && Bug Hunter


Did you replicate this project? Share it!

I made one

Love this project? Think it could be improved? Tell us what you think!

Give feedback


Sign up / LoginProjectsPlatformsTopicsContestsLiveAppsBetaBlog