A Guide to Measuring Distance with HC SR04 Sensor Using Raspberry Pi

Raspberry Pi allows you to get creative with programming and build stuff with it. With the Pi, you can make your code come alive. This is the reason I love working with Raspberry Pi and today, we will be talking about one cool Raspberry Pi project: measuring distance using an HC SR04 sensor.

We will discuss what an HC SR04 is and the principle on which it functions. Moreover, we will also discuss the possible use cases of this sensor and a small Python project that you can easily do it too and implement in your own house. So let us quickly look at the topics we will go through and get started:

hc sr04

What is the HC SR04 sensor?

HC SR04 sensor is a distance-measuring sensor module that is developed for small electronic and programming projects. It is designed to measure distances by sending out ultrasonic sound waves and then timing how long it takes for the sound waves to bounce back after hitting an object. The sensor consists of an ultrasonic transceiver module, which includes both a transmitter and a receiver for emitting and receiving the signal waves.

How does the sensor work?

To start the measurement, you send a pulse to the trigger pin of the sensor through which, the emitter of the sensor sends out ultrasonic waves. This is called the trigger signal. These waves hit the object in front and are reflected, which ultimately are received by the receiver of the sensor. The receiver detects these reflected signals and generates an electrical pulse.

So how does this help in measuring the distance? Ultrasonic waves travel at the speed of sound, i.e. 343 m/s. The time taken by the waves to travel and reflect to the sensor is called flight path. So, when we multiply the flight path with the speed of sound and divide it by 2, we get the distance of the object from the sensor.

Distance = (Time * Speed of Sound) / 2

Python project to measure distance using HC SR04 sensor

In this small Python project, we are going to write code to measure the distance of some objects using Raspberry Pi and the sensor. Understandably, these two pieces of hardware are necessary for the project. If you already have them, you’re good to go. If not, I’ve got your back. You can easily buy both of them on Amazon. Both of them together will cost you just $50. Use the affiliate links below to buy the products. It won’t cost you anything extra but would make a small amount of money if you use the link for the purchase.

Buy Raspberry Pi from Amazon
Buy HC SR04 Ultrasonic Sensor from Amazon

Anyway, now that you know what hardware you require, let us get started.

import RPi.GPIO as GPIO
import time

# Set the GPIO mode to BCM
GPIO.setmode(GPIO.BCM)

# Define the GPIO pins for the ultrasonic sensor
TRIG_PIN = 23
ECHO_PIN = 24

# Set up the GPIO pins
GPIO.setup(TRIG_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)

def measure_distance():
    # Ensure the TRIG pin is low
    GPIO.output(TRIG_PIN, False)
    time.sleep(0.1)

    # Send a 10us pulse to trigger the ultrasonic sensor
    GPIO.output(TRIG_PIN, True)
    time.sleep(0.00001)
    GPIO.output(TRIG_PIN, False)

    # Record the start time
    while GPIO.input(ECHO_PIN) == 0:
        pulse_start = time.time()

    # Record the end time
    while GPIO.input(ECHO_PIN) == 1:
        pulse_end = time.time()

    # Calculate the pulse duration
    pulse_duration = pulse_end - pulse_start

    # Speed of sound is 343m/s, so distance = speed * time / 2
    distance = (pulse_duration * 343) / 2

    return distance

try:
    while True:
        # Measure distance and print the result
        distance = measure_distance()
        print(f"Distance: {distance:.2f} m")

        # Wait for a short time before the next measurement
        time.sleep(0.01)

except KeyboardInterrupt:
    print("Measurement stopped by the user")
    GPIO.cleanup()

Breaking Down the Code

1. Import Libraries

import RPi.GPIO as GPIO
import time

  • RPi.GPIO is a Python module to control and access GPIO pins on the Raspberry Pi.
  • time module provides various time-related functions.

2. Set GPIO Mode and Define Pins

GPIO.setmode(GPIO.BCM)
TRIG_PIN = 23
ECHO_PIN = 24

  • GPIO.setmode(GPIO.BCM) sets the GPIO pin numbering mode to Broadcom SOC channel numbers.
  • TRIG_PIN and ECHO_PIN are the GPIO pins connected to the trigger and echo pins of the ultrasonic sensor, respectively.

3. Set Up GPIO Pins

GPIO.setup(TRIG_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)

  • GPIO.setup() is used to set up the specified pin as an input or output.

4. Define the measure_distance Function

def measure_distance():

  GPIO.output(TRIG_PIN, GPIO.HIGH)
  time.sleep(0.00001) GPIO.output(TRIG_PIN, GPIO.LOW)
  
  while GPIO.input(ECHO_PIN) == 0:
    pulse_start_time = time.time()
    
  while GPIO.input(ECHO_PIN) == 1:
    pulse_end_time = time.time()
    pulse_duration = pulse_end_time - pulse_start_time
    distance = (pulse_duration * 34300) / 2
    return distance
  • measure_distance function triggers the ultrasonic sensor, measures the time it takes for the echo signal to return, and calculates the distance using the speed of sound formula.

5. Main Program

try:
  while True:
    dist = measure_distance()
    print(f"Distance: {dist:.2f} cm")
    time.sleep(0.1)
  
except KeyboardInterrupt:
  GPIO.cleanup()
  • The try block contains a loop that continuously measures the distance using the measure_distance function, prints the result, and then sleeps for 1 second.
  • The except KeyboardInterrupt block is used to handle a keyboard interrupt (Ctrl+C), and it cleans up GPIO pins using GPIO.cleanup() before exiting the program.

6. Run the Script

python3 main.py

  • Run the script and put some object before the sensor. Move it to and fro and watch the change in distance values.

Adjust the GPIO PINs in the code based on your actual hardware connections. This script provides a basic example of measuring distance using an ultrasonic sensor with a Raspberry Pi.

Possible Use-Cases/ Application of the HC SR04 sensor

Now that you know how to measure the distance of an object using the sensor in Python, you can build various things at home itself, such as:

  • Water level detection: Determine the water level in the tank using the sensor and let the code notify you by turning on a red LED once the water level is above a threshold distance.
  • Home-made parking sensor: Mount the Raspberry Pi along with the sensor on the rear of your car and let it send a warning tone once the distance to the wall is less than the threshold distance.
  • Smart doorbell system: Place the sensor near the main door of your house. Program it such that if there is a visitor, it will send your a mobile notification or take the picture of the visitor and email it to you.

Conclusion

In this blog, we understood how an HC SR04 distance-measuring sensor module works and we wrote a small Python code to measure distance. We also saw a few possible applications of the project that you can try out today. Feel free to play around with the code and modify it according to your wish. I would like it if you too came up with some creative ideas on this topic. The idea does not have to be extraordinary; it can be as simple as detecting the distance of a coffee mug from the sensor. But the main idea is about watching how your code will function, and if it functions the way you expect it to.

Now I believe that you found this project in Raspberry Pi fun and interesting, didn’t you? Well, go ahead an try another one where you’ll write Python code to get GPS coordinates of your location using Raspberry Pi.
OR, you can also read gyroscopic data using Raspberry Pi. Go ahead and try both of them and let me know your experience with those projects.

Feel free to get in contact on Instagram: @machinelearningsite. If you happen to build any project, you can tag me in it and it would be great to see it. Apart from that, get in touch on my social media:

If you are interested in such topics, it would be a shame if you missed any blog. To avoid that, join the FREE newsletter:

Leave a Reply