Posted on Leave a comment

The HC-SR04 ultrasonic distance sensor on a Raspberry Pi

In this tutorial we use an ultrasonic sensor to measure distances. With a Python script on our Raspberry Pi, we calculate the distance to an object. When you have completed this tutorial, you will be able to connect the HC-SR04 sensor to your Pi via the GPIO pins. You’ll also have the basic elements to convert via a Python script the measurements from the sensor to a measured understandable distance .

  1. Prepare your Raspberry Pi

    First, you need to have a Raspberry Pi running on the latest version of Raspberry Pi OS. This version includes “Thonny”. We’ll use this user-friendly IDE to write our Python code. If you’re not familiar with Python or with Thonny or GPIO-pins, I suggest to have a look at our tutorials “How to write your first Python program on the Raspberry Pi” and/or “How to use the Raspberry Pi GPIO pins” to have a quick introduction.

  2. Prepare the extra hardware

    Next you’ll need some extra hardware:
    – a breadboard (we are using a 400 points breadboard)
    – an HC-SR04 ultrasonic sensor
    – a 1k Ohm and a 2k Ohm resistor
    – Dupont jumper wires
    – a T-cobbler (optional)
    – a 40 pin GPIO cable (optional)

    If you miss any hardware, don’t hesitate to visit our shop. We have a nice kit which contains all the things you need tot start. Raspberry Pi GPIO kit

  3. Get to know the HC-SR04 ultrasonic sensor

    The HC-SR04 ultrasonic sensor uses the sonar principle to determine the distance to an object. It offers a contactless measurement with good accuracy and stable readings. On the module we find an ultrasonic transmitter and a receiver. The sensor has a range of 2 to 400 cm. The accuracy of the measurement is +/- 0.5 cm.

    The sensor uses ultrasonic sound signals to define the distance:
    – The transmitter sends an audio signal in the direction of the object.
    – When the signal reaches the object, it is reflected back to the sensor.
    – The receiver can detect the reflected signal.

    We can calculate the time difference between the time when the transmitter sends the signal and the time when the receiver picks up the signal. Since the speed of the sound is known (343.3 m / s or 34330 cm / s) we can now calculate the distance:

    distance = speed * time , or in our case:
    distance = 34330 * time / 2 , or distance = 17165 * time

    Note: Since the measured time takes into account the distance from the sensor to the object and the distance from the object to the sensor, we must divide this observed time by 2.HC-SR04 ultrasonic distance sensor
    Be careful ! Before starting to connect wires on the GPIO pins of your Raspberry Pi, make sure you properly shut down the Pi and removed the power cable from the board!

  4. Setup the hardware

    raspberry pi HC-SR04 ultrasonic distance sensor– connect the 40 pin cable on the GPIO pins of your Pi (if necessary, remove the cover of your Pi first)
    – plug the cobbler onto the breadboard as shown in the figure above or below
    – plug the other end of the 40 pin cable in the T-cobbler
    – connect the VCC pin of the sensor with a 5V pin (red wire)
    – connect the Trig pin of the sensor to pin 23 (green wire)
    – connect the Echo pin of the sensor to the 1kOhm resistor, connect the other end of the resistor to pin 24 (yellow wire)
    – connect the GND of the sensor to the “-” row of the breadboard and also connect the GPIO GND to the “-” row of the breadboard (black cable)
    – insert the 2kOhm resistor between pin 24 and the “-” row

    The 2 resistors are used to reduce the voltage of the Echo signal from 5V to 3.3V. Connecting the Echo pin directly to a GPIO pin (provided for 3.3V) could damage it. We do this on the basis of the “Voltage divider” principle.

    Raspberry Pi HC-SR04 ultrasonic distance sensor

  5. Write the code

    The goal is to write a very basic Python program that allows us to compute a distance in cm between the ultrasonic sensor and an object. To write the code, we use the Thonny IDE. You can find Thonny under the application menu of your Raspberry Pi.

    Write or paste following code in the IDE:

    import RPi.GPIO as GPIO
    import time
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    TRIG = 23
    ECHO = 24
    GPIO.setup(TRIG,GPIO.OUT)
    GPIO.setup(ECHO,GPIO.IN)
    GPIO.output(TRIG, False)
    print ('Waiting a few seconds for the sensor to settle')
    time.sleep(2)
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    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 * 17165
    distance = round(distance, 1)
    print ('Distance:',distance,'cm')
    GPIO.cleanup()

    Some explanations about the code:

    GPIO.setmode (GPIO.BCM): The GPIO.BCM option means that we are referring to the pins by the “Broadcom SOC channel” number, these are the numbers after “GPIO”
    GPIO.setwarnings (False): We use this line of code to avoid warning messages.
    GPIO.setup(TRIG,GPIO.OUT): We define the TRIG-pin (= 23) as an output pin
    GPIO.setup(ECHO,GPIO.IN): We define the ECHO-pin (= 24) as an input pin
    GPIO.output(TRIG, False)
    print ('Waiting a few seconds for the sensor to settle')
    time.sleep(2)
     We put the TRIG-pin low and wait for 2 seconds
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)
     then we send a 10 µs pulse with the TRIG-pin
    while GPIO.input(ECHO)==0:
    pulse_start = time.time()
     this is a loop that allows us to record the last timestamp before the signal reaches the receiver.
    Be careful, Python is whitespace-sensitive. Don’t remove the “tab” before the code line after the while command.
    while GPIO.input(ECHO)==1:
    pulse_end = time.time()
     here we register the last timestamp at which the receiver detects the signal. Namely, the receiver will start receiving a direct signal until the reflected signal is finally received.
    pulse_duration = pulse_end - pulse_start we calculate the time difference between both timestamps
    distance = pulse_duration * 17165 we calculate the distance based on the calculated time (see explanation in previous paragraph)
    Finally, we round the result with one decimal, we print the result and reset the GPIO pins.

  6. Run the Python script

    Before running the program you’ll have to give it a name and save it.

    raspberry pi python HC-SR04

    Once saved, point the sensor to an object with a flat surface and click on the Run button. You will see the distance between the sensor and the object appear on the screen as a result.

    Be careful with other objects nearby. These could also send an echo. Which would then give you incorrect measured values.

Congratulations! With this setup you do understand now the principle of how some distance meters function. You can further use the script to process the result in an application where you want to measure or monitor a certain distance yourself. Have fun with it!

How useful was this post?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 6

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

How useful was this post?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 6

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

find out more products

Be the first to be informed about our latest tutorials and products by subscribing to our Newsletter

freva.com respects your privacy. Read our privacy policy on how we handle your personal information.