Using a Raspberry Pi distance sensor (ultrasonic sensor HC-SR04)

For many (outdoor) projects a distance measurement is necessary or advantageous. These small modules are available starting at 1-2 bucks and can measure the distance up to 4-5 meters by ultrasound and are suprisingly accurate. This tutorial shows the connection and control.



  • HC-SR04 Module (US / UK)
  • Resistors: 330Ω and 470Ω (US / UK)
  • Jumper wire (US / UK)


There are four pins on the ultrasound module that are connected to the Raspberry:

  • VCC to Pin 2 (VCC)
  • GND to Pin 6 (GND)
  • TRIG to Pin 12 (GPIO18)
  • connect the 330Ω resistor to ECHO.  On its end you connect it to Pin 18 (GPIO24) and through a 470Ω resistor you connect it also to Pin6 (GND).

We do this because the GPIO pins only tolerate maximal 3.3V. The connection to GND is to have a obvious signal on GPIO24. If no pulse is sent, the signal is 0 (through the connection with GND), else it is 1. If there would be no connection to GND, the input would be undefined if no signal is sent (randomly 0 or 1), so ambiguous.

Here is the structure as a circuit diagram:


Script for controlling

First of all, the Python GPIO library should be installed

To use the module, we create a new script

sudo nano

with the following content:

After that we run:

sudo python

So every second, the distance will be measured until the script is cancelled by pressing CTRL + C.
That‘s it. You can use it many fields, but who still want to measure larger distances would have to rely on laser measuring devices, which, however, are much more expensive.

67 Responses

  1. Thank you, I need this for a Magic Mirror. I want it to activate when someone is nearby, in front.
    I have experimented with PIR, I always seem to find them a bit random but this should be good.
    I found other examples of “how to do this”. This one, yours, worked immediately.

    OK, so it is not my solution and I need to do much more to make my exact application work but “Thank You” so much for this proof of concept.

      • Really the objective of those pair of resistors ( R1 & R2), is create a tension divisor in order to reduce the 5volt dc of the echo of the module SH-04 pin to less than 3.3 volt, because the GPIO (input dc or Out dc), operation voltage in all rtaspBerry Pi boards is 3.3 volts (Prof. JCGM) 🙂

  2. Thank you for making it so easy to get playing with this sensor.

    I only had 1k and 2.2k resistors available. Would that be the reason my measurements are off by about 1.7cm on the distances (0.5 – 2 meters) I tested?

    My understanding is that a higher resistor will merely pull the voltage even lower than the target 3.3V needed to make the echo response safe for the pi’s GPIO pins.

    Thanks again

    • Might be too late, but for future readers… it actually doesn’t make a difference. As long as the pi recognizes the signal as a high, it works. The only two possible outcomes are: 1. the pi doesn’t receive the high signal and your program either handles this, crashes, or runs forever because it’s waiting to receive a high or 2. the pi recognizes the signal as a high and therefore no error due to the pi/wiring/sensor. You could create a calibration curve for your sensor if you want the distances to be perfect. Also don’t forget that you’re doing the computation for the distance, so the speed of sound through air at the ambient temperature must be set properly for your ambient temperature.

      • Hey, I have problem where when I read the distance measurements on the sensor in loop, it reads 4-5 measurements and then it freezes on the terminal for a few seconds and then it starts reading in measurements again. I’m not sure what the problem do this issue is and how to fix this, I need the sensor to continuously measure the distance without pausing

  3. I used this code and wired the circuit correctly with the 330 and 470 Ohm resistors but am getting values of over 100,000 cm even though my sensor is only 1 meter from a wall. Any ideas?

  4. Hi.

    I’ve made this and it worked perfect.

    But i need to show it’s output in a webpage i configurated with lighttpd.

    i know the page needs to be updated often. so i’ve done the following:

    function() {window.location.reload();},

    Here goes the whole page:

    TCC – MEM


    function() {window.location.reload();},

  5. it depends of the materal of the wall, if it’s made of glass, the distance gonna be different, just like as wool.

  6. Hi, I need to connect 2 ultrasonic sensonrs and 1 gps, What pins should I use for the connection?

  7. HI! was thinking of use this in my backhoe mount the sensor on the digging arm and messure down to digging level would it work ?? there is no digging system´s for home use… please leave a comment if this is possibel

    • Re: mount in backhoe … two significant challenges beyond mounting it somewhere it can make the measurement and, assuming that it’s not mounted on the cab, finding shielded cable with fine stranding and soft insulation that can withstand the bending at the arms joints, and a flexible plastic armor to encase it in.
      The sensor measures the time delay of a sonic echo returning to infer distance. The echo from a hard flat surface is easy to interpret. The echo from a complex surface of stone(s), hard packed natural contour, loosened earth and material falling/fallen back into the hole will be a more complex and return from the sides of the hole will mimic a soft bottom to some extent, making it even more difficult to determine the hole depth. You may need multiple sensors to determine what’s happening at the sides of the hole to determine what’s happening at the bottom.
      The sensor, whether mounted on the cab or the hydraulic arm will be mounted on a platform attached to a steel structure that transmits and mechanically amplifies vibration. The components aren’t made for that environment. Everything changes when it has to operate in a vibrating environment, even the choice of solder alloy. Subjecting the raspberry pi components to any significant vibration may shorten the operating life to minutes/hours/days. Make sure modules with clock circuits use a ceramic resonator not a quartz crystal. It will also add a large interfering signal to the echo return signal picked up. One of the key steps to making a successful sensor is going to be isolating the sensor platform from the vibration of the excavating machine. One way to avoid multiple evolutions of a vibration damping scheme is to begin with a multiple step approach something like conventional rubber vibration mounts to fix an 1/8 inch thick steel plate and then a layer of cork/tar adhesive to fix a lower mass aluminum plate to secure a sensor housing. Secure the cable in a flexible shape (a hairpin bend, an S bend, or a clock spring spiral in order of isolation and durability) to avoid transmitting vibration up the cable. It may or may not be necessary to do something more elaborate depending on the design details.
      Once you get something mounted cover the sensor(s) with something like polyester cushion fill and get the signal is quiet enough to make figuring out the echo signal from the hole so you aren’t measuring vibration from the engine, hydraulic system, and boom arm as much as the hole.
      If low cost ultrasonic distance sensors aren’t effective in this environment then an optical approach using something more like what a camera uses for infrared assisted autofocus may work.

  8. Hello. I have a QUESTION. Do I first need to install Raspbian to create the python code in the raspberry Pi, or can I just create the Python file in my own computer and then move it to the Raspberry?

  9. You should be able to do it anywhere and transfer, but you have to remember to check if you need to do chmod for executables

  10. Tried it and it worked at the first test. Almost creepy. But very cool!!
    Thanks for this guide.

  11. 1)Why should to send trigger high and low , please explain working of ultrasonic sensor.

    2)why StartTime = time.time()
    StopTime = time.time()
    Are initialised ,you can directly use in while statement isn’t it?

    • It frequently turns speaker on which causes ultrasound, the ultrasound bounce off the object its aiming on and it comes back to sensor, and the time between the response of time of that sound coming back is calculated and this measure the distance…

  12. These look really cool!
    I have use case where I would like to use multiple sensors in the same area.
    Is there a way to set a unique frequency or amplitude (or any other attribute) of the ultrasonic signal so I can track which transmitter is heard by the receiver?
    Thanks for any help!

    • I realize a simple solution would be to alter the timing of the transmissions, but I prefer to be able to just track each reception by source-of-signal rather than when the signal was received, if that’s possible.

      • The sensor has 2 piezo electric benders one for TX one for RX. The TX bender is driven with a step wavefront and the RX sensor gets a direct echo magnitude vs time. You could try to add something to absorb off-angle pulses to reduce interference if the sensors point in different directions but there’s no pre-made hardware that uses a more elaborate waveform that could be code division multiplexed or frequency division multiplexed to allow co-located sensors to operate simultaneously without interfering with each other. An optical method distance sensor, an IR distance sensor for example, might suit your need if sensors are intended to point in different directions.

    • turned out I looked at the wiring diagram of a different article on my phone then got to this page on my pc

  13. i would like to call a script when an object is within range 0-100cm, please. I would like to ask how could i modify the aforementioned script please?

  14. Do we need to use a 5V to 3.3V convertor for this? I was advised to use it when working with sensors as an overload can mess up the GPIO part of the Raspberry Pi.


Leave a Comment

Your email address will not be published.

Subscribe to Raspberry Pi Tutorials and don't miss any new Tutorial!