Tested on:Raspberry Pi 2; Raspberry Pi B+; Python 2.7; Raspbian pre Jessie
Prerequisites:Raspberry Pi with Raspbian Jessie and internet connection (see steps 1-7 in the Introduction)
Building a simple LED display (optional)
Hardware:5V ultrasonic sensor, e.g. HC-SR04

Ultrasonic range detection with the Raspberry Pi

Ultrasonic is one of many options for measuring distance with a Raspberry Pi. This tutorial shows how to use an ultrasonic sensor with 5V operating power from the Raspberry Pi. Since the Raspberry Pis maximum input voltage is 3.3V and the signal delivers 5V, a voltage divider has been added. For some sensors (see datasheet), 3.3V operating power (pin 1) can be used instead without a voltage divider, but the range will be lower.
The LED display from the prerequisites is optional and just used for demonstrational purposes. The code will work without.

Voltage divider
Here is the circuit schematic with the voltage divider:

 Ultrasonic Sensor on a Breadboard

Ultrasonic Sensor on a Breadboard

For this voltage divider, two 10k Ohm resistors were soldered straight into the jumper cables.
Ultrasonic sensor Voltage Divider

Ultrasonic sensor Voltage Divider

White is echo and pin 40, gray is trig and pin 38, red/violet is +5V and pin 2 and black is pin 6, GND.

Script installation and usage
Download the scripts with

then start the range detection with

The distance will be printed to the terminal.

Code explained
The main loop displays the distance as one LED per 5cm. The distance is calculated in this piece of code:

First, a signal of shortest duration is fired with trig. Then, echo listens for the moment the reflected signal enters and leaves the sensor, which gives the runtime.

Measuring the distance with Python is not very accurate, since Python has a low real-time precision.
Alternatively, calling a c-based version from Python may have higher precision.

Sensor and LED display

Raspberry Pi and ultrasonic sensor

Raspberry Pi and ultrasonic sensor

The complete script
Click on Full Script to show all of the code.

In action

SparkFun on Voltage Dividers: https://learn.sparkfun.com/tutorials/voltage-dividers

Knight of Pi

Johannes Bergs aka Knight of Pi. Diploma in Bioinformatics, some Webdesign and Python coding then. Living in the beautiful city of Vienna.


  1. Hello, I did the same with the 2 resistances of 10k (so we have 2.5v for echo) but some of my values are too far from reality (for a fuel tank) … Is it a problem of voltage? If I add a resistance of 10k (in series) to the ground the voltage will be 3.3v (GPIO voltage) : can it be better for you? Thanks !

    • Hi,

      i’m having that problem as well, some of the detected values are way off. I do not have a clean solution for this, but, in respect of the specific task, there might be some simple statistics than can solve your issue. For a fuel tank, i’d just use a sliding window of values, say, the average of five values, and exclude measurements that are too far off. Hope this helps!

  2. My sensor is constantly reading 3000cm. That doesn’t seem right at all. I’ve validated that my voltage divider works properly 5v -> 3v. I have modified the pin numbers to accommodate my case, but I have validated that they work properly by looking at “gpio readall” and making sure that the states were set right. I have also tried with another sensor & tried a vanilla Raspbian/Jessie but I’m still getting the same results. Any clues?

    • Strange. I’d recommend retrying with the pins used in the tutorial. If it still doesn’t work, mail me a photo of your circuit.

  3. need help, I want to try to enable or disable the sensor with a function of time, for example, I want to turn the sensor on the hour 11:25 pm and switched off at 12:00 hours, I use python

  4. hello
    I got a problem … the running stop at this line

    while GPIO.input(echo) == 0: pass
    start = time.time() # reached when echo listens

    without display any running error .
    just stoped there

    • Hi Hamza,

      that’s either the wiring or a defect of the sensor or the Raspberry Pi.

      If you have a voltmeter, you could attach it in parallel between ECHO on the sensor side and to the RPi ground pin 6. Without running the script, the voltmeter should read something below 4 Volt. When the script is run, the voltage goes to zero fast, but rises to ~ 0.001 Volt again for a very short time. If that doesn’t happen, it’s likely the sensor.

      Also, try using other pins then 38 and 40 for ECHO and TRIG! Just change the pins in the circuit to, say, 15 and 16, then change the constants at the beginning of the script accordingly.

  5. hi, that’s grate
    i make this project, but not work for long time. after some minutes program stopped.

    • Hey Taha,

      interesting, i really don’t know why that happens. I’m currently working on a project with these ultrasonic sensors, i’ll update in a few days if i’m having the same problem.

      Did you get any error message btw?

      • hi,
        the beginning of the project this error:
        Warning (from warnings module):
        File “/home/pi/LED.py”, line 7
        GPIO.setup(pins, GPIO.OUT)
        RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.

        Warning (from warnings module):
        File “/home/pi/distancultra.py”, line 12
        GPIO.setup(trig, GPIO.OUT)
        RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
        after that program running correctly.

        • Hi Taha,
          these warnings are not a problem- the pins were configured differently and that makes the GPIO module output a warning.

          I just tried the script and let it run for more then 15 minutes without any errors,
          so i don’t know why it doesn’t work for you.

          Are you using a HC-SR04 ultrasonic? Is your operating system an updated Jessie?


Time limit is exhausted. Please reload CAPTCHA.