sajo.joseph.3333
Posts: 2
Joined: Sun Feb 15, 2015 8:39 am

HC-SR04 ultrasonic sensor and raspberry pi

Wed Feb 18, 2015 2:05 am

How to connect hc-sr04 module with raspberry pi ? One is a 5v device while other is 3.3v device.

User avatar
B.Goode
Posts: 7868
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: HC-SR04 ultrasonic sensor and raspberry pi

Wed Feb 18, 2015 8:04 am

If you put your question "How to connect hc-sr04 module with raspberry pi" into your preferred web search tool you will get many helpful results.

Those from modmypi and raspberrypi-spy seem to be clearly written.

texy
Forum Moderator
Forum Moderator
Posts: 5156
Joined: Sat Mar 03, 2012 10:59 am
Location: Berkshire, England

Re: HC-SR04 ultrasonic sensor and raspberry pi

Wed Feb 18, 2015 1:02 pm

Hi,
the search facility on this forum is a bit limited as it will the take the '-' as a directive, but if you just search for "SR04", you will get hits :
http://www.raspberrypi.org/forums/searc ... words=SR04

Texy
Various male/female 40- and 26-way GPIO header for sale here ( IDEAL FOR YOUR PiZero ):
https://www.raspberrypi.org/forums/viewtopic.php?f=93&t=147682#p971555

lijoppans
Posts: 3
Joined: Sun Feb 15, 2015 8:36 am

Re: HC-SR04 ultrasonic sensor and raspberry pi

Thu Feb 19, 2015 4:51 am

You can directly connect 3.3V output of Raspberry Pi to TRIGGER input of HC-SR04. It will detect 3.3V as HIGH LEVEL.
But the 5V ECHO output of HC-SR04 should not be directly connected to 3.3V rated Raspberry Pi input.. It may damage it.. So you should use additional voltage dividing resistors to reduce 5V to 3.3V compatible with Raspberry Pi... You can use a 10K and a 4.7K resistor for that.
. Rest is very easy...

> Provide TRIGGER to Raspberry Pi
> Listen for ECHO
> Measure the time period of ECHO
> Convert it to Distance by using Speed Distance Time Equation

Here is python code :

Code: Select all

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
  else:
    print "Out Of Range"                   #display out of range
This code uses PIN 23 as TRIGGER and PIN 24 as ECHO.

Source :
Interfacing HC-SR04 Ultrasonic Sensor with Raspberry Pi

User avatar
joan
Posts: 14013
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: HC-SR04 ultrasonic sensor and raspberry pi

Thu Feb 19, 2015 8:06 am

Code examples on the www are just examples.

The following is more reliable and won't crash out with undefined pulse start or end.

Code: Select all

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

   pulse_end = pulse_start      # last known time of HIGH pulse
   while GPIO.input(ECHO)==1:
      pulse_end = time.time()   # last known time of HIGH pulse

cia48621793
Posts: 39
Joined: Wed Feb 18, 2015 8:24 am
Location: Hong Kong

Re: HC-SR04 ultrasonic sensor and raspberry pi

Thu Feb 19, 2015 9:06 am

This is the pseudo-code of how it works, notice it's a dialect of C:

Code: Select all

int triggerPin = 1;
int echoPin = 2;

main()
{
    pinMode(triggerPin, out);
    pinMode(echoPin, in);
}

unsigned int highTime;
velocity speedOfSound = 340m/s;
loop()
{
    if (action->useSensor did not occur)
       continue loop();
     setPin(echoPin, low);
     setPin(triggerPin, high);
     sleep(10 microseconds);
     int oldTime = timeOfNow();
     Blocking()
     {
          if (waitForHighPulse(echoPin)) // or pulseIn
             highTime = timeOfNow() - oldTime;
     }
    int time = highTime / 2; // When the ultrasound hits the object or surface, it reflect backs to the receiver with the same distance of how far the hit distance have made, so we divide it by two.
   int cmOfSoundSpeedPerMicroSeconds = getDistance(speedOfSound) * 100 / getTime(speedOfSound) * 10^6;
   // = (340m*100) cm / (1s*10^6) us = 0.034 cm/us
   int cm = time * cmOfSoundSpeedPerMicroSeconds;
   omitToConsole(cm); // This is centimeter distance, for inch, multiply this value by 2.54, omitToConsole(cm*2.54)
}
Hope this helps you.

Adilkhan
Posts: 2
Joined: Fri Apr 03, 2015 6:27 am

Re: HC-SR04 ultrasonic sensor and raspberry pi

Fri Apr 03, 2015 6:31 am

how to connect ultrasonic sensor HC-SR04 to raspberry pi b 2 ?i tried connect ultrasonic sensor HC-SR04 to raspberry pi b(not b 2) it is worked

robopie
Posts: 1
Joined: Sun Sep 13, 2015 1:50 pm

Re: HC-SR04 ultrasonic sensor and raspberry pi

Sun Sep 13, 2015 1:52 pm

Hi, my pi doesn't "understand" the import line ....


HELP !!!

:o :o :o

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: HC-SR04 ultrasonic sensor and raspberry pi

Sun Sep 13, 2015 6:52 pm

I think you'd be better off starting a new post and including your code and error message.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Return to “Python”