Posted on

HC-SR04 Ultrasonic sensor on Raspberry Pi

In this tutorial we use an ultrasonic sensor to measure distances. With a Python script on your 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 the measurements from the sensor to a measured distance via a Python script.

What you’ll need for this tutorial

First, you need to have a Raspberry Pi 3 running on the latest version of Raspbian. 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 “First Python program on the Raspberry Pi” and/or “Raspberry Pi first program using GPIO” to have a quick introduction.

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)

Raspberry Pi GPIO discovery kit

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

 

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.

Setting up the hardware part

Before starting connecting wires on the GPIO pins of your Raspberry Pi, make sure you properly shut down the Pi and removed the power cable of the board!

HC-SR04 ultrasonic sensor connected to Raspberry Pi
  • 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
HC-SR04 ultrasonic sensor connected to Raspberry Pi

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.

Writing the code

The goal is to write a very simple 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.
HC-SR04 ultrasonic sensor Python script

When you are done with the code, 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 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!