Distance Sensing With Raspberry Pi and HC-SR04

Introduction: Distance Sensing With Raspberry Pi and HC-SR04

The HC-SR04 Ultrasonic Distance Sensor uses non-contact ultrasound sonar to measure the distance to an object. It consists of two transmitters, a receiver and a control circuit. The transmitters emit a high frequency ultrasonic sound, which bounce off any nearby solid objects, and the receiver listens for any return echo. That echo is then processed by the control circuit to calculate the time difference between the signal being transmitted and received. This time can subsequently be used, along with some clever math, to calculate the distance between the sensor and the reflecting object!


What you will need:

  • Raspberry Pi 2/3/4
  • Micro SD Card loaded with Raspbian
  • 5.1V USB Power supply
  • HC-SR04 (obviously)
  • Breadboard
  • 4 Male to Female Cables
  • Monitor and keyboard for Raspberry Pi

Step 1: Set Up the Raspberry Pi

  1. Insert the SD card you’ve set up with Raspbian (via NOOBS) into the microSD card slot on the underside of your Raspberry Pi.

  2. Find the USB connector end of your keyboard's cable, and connect the keyboard to a USB port on Raspberry Pi (it doesn’t matter which port you use).

  3. Make sure your screen is plugged into a wall socket and switched on. Look at the HDMI port(s) on the Raspberry Pi — notice that they have a flat side on top. Use a cable to connect the screen to Raspberry Pi’s HDMI port — use an adapter if necessary.

  4. Plug the USB power supply into a socket and connect it to your Raspberry Pi’s power port.

  5. Your Raspberry Pi will start booting up then you will be ready to go.

Step 2: Setting Up the Hardware

Setting up the ultrasonic distance sensor is fairly simple, no other complicated parts needed, just the sensor, 4 cables and the Raspberry Pi. It only has four pins:

  • VCC to Pin 2 (5V)
  • TRIG to Pin 12 (GPIO 18)
  • ECHO to Pin 18 (GPIO 24)
  • GND to Pin 6 (GND)

Step 3: Python Script

Firstly we should have the python gpiozero library installed and to use we will create a new script

sudo nano distance_sensor.py

with the following:

# Getting the libraries we need
from gpiozero import DistanceSensor
from time import sleep

# Initialize ultrasonic sensor
sensor = DistanceSensor(trigger=18, echo=24)

while True:
	# Wait 2 seconds
	# Get the distance in metres
	distance = sensor.distance

	# But we want it in centimetres
	distance = sensor.distance * 100

	# We would get a large decimal number so we will round it to 2 places
	distance = round(sensor.distance, 2)

	# Print the information to the screen
	print("Distance: {} cm".format(sensor.distance))

Be the First to Share


    • Battery Powered Contest

      Battery Powered Contest
    • Plywood Challenge

      Plywood Challenge
    • Plastic Contest

      Plastic Contest