How To Control a Ultrasonic Distance Sensor with Raspberry PI

Check my RPI articles in Best Raspberry PI projects article or home page. Or subscribe my newsletter (top right in this page) to be notified when new projects are available! Also interested to start 3D printing with a cheap budget? Visit my cheap 3D printers list
HC-SR04 Ultrasonic Sensor

Ultrasonic Sensor is great for all kind of projects that need distance measurements, avoiding obstacles as examples. The HC-SR04 is inexpensive and easy to use.

Ultrasonic sensor module HC-SR04 provides 2cm-400cm non-contact measurement function, the ranging accuracy can reach to 3mm.

Ultrasonic sensor module HC-SR04 measures distances between 2cm and 400cm. Accuracy can reach to 3mm. The basic principle of work:

  • IO trigger high level signal (for at least 10us) starts the process
  • The module automatically sends eight micro signals at 40 kHz and starts to ear to detect whether there is a feedback signal back.
  • If there is a signal back, the time of high input IO duration is the time taker for ultrasonic to hit object and turn back.

So, distance = (high level ingress duration × speed of sound (34300cm/s) / 2.

The final bivision by is because we have a feedback for roundtrip, distance is the half.

The Timing diagram is shown below:

HC-SR04 timing diagram

A warning comes from voltage levels. HC-SR04 module works with 5V current (except from trigger, which can be a lower) and outputs a 5V signal on echo. Echo goes back to Raspberry PI for duration measurement on GPIOs. Raspberry PI GPIO reading should be at 3,3V to avoid circuit failure, so we need to implement a simple voltage reduction circuit with resistors.

A good explaination comes from How to Reduce Voltage with Resistors. Our voltage circuit will follow this organization diagram:

RPI HC-SR04 resistore organization

Calculations are according to following formulas:

So, once defined:

  • Vgpio = 3,3 Volt,
  • Vecho = 5 Volt

We choose R1 and derive R2 from following:

In my kits, I have 100 Ohm resistors, so I use it for R1. From last equation I need to supply a 194,12 Ohm from R2, but I have only 100 Ohm and 220 Ohm resistors. Instead of using a 220 Ohm resistor with 10% of error margin, I use for R2 two 100 Ohm resistors in series, so that resulting value is returned by their sum (200 Ohm). Final voltage reduction circuit is:

RPI HC-SR04 resistore implementation

Now we can start our project.

In this article we’ll control our HC-SR04 ultrasonic distance sensor from a Raspberry PI Zero W. This article applies also to newer Raspberry PI boards.

What We Need

Raspberry PI Zero WH board

As usual, I suggest adding from now to your favourite ecommerce shopping chart all needed hardware, so that at the end you will be able to evaluate overall costs and decide if continuing with the project or removing them from shopping chart. So, hardware will be only:

Many of listed hardware (except from Raspberry PI Zero W and micro SD Card) can be bought alone or can be also found in the useful Elegoo starter kit.

Check hardware prices with following links:

Amazon raspberry pi boards box
Amazon raspberry pi Zero W box
Amazon Micro SD box
Amazon Raspberry PI Power Supply box

Step-by-Step Procedure

Wiring Diagram

Prepare cabling according to following wiring diagram:

RPI HC-SR04 wiring diagram

Please find below the overall picture:

Raspberry PI HC-SR04 picture 2
Raspberry PI HC-SR04 picture

OS Preparation

Start with OS installation using install Raspberry PI OS Lite guide. This procedure also works with Raspberry PI OS Desktop, using its internal terminal.

Make your OS up-to-date:

sudo apt update
sudo apt upgrade

Python Scripting

Install GPIO

sudo apt install rpi.gpio

Get from my download area script:


Script Usage

This script can be used by simply calling from terminal:


It will start measuring objects distance showing it in cm.

To stop the program, just press CTRL+C

Script explaination

First of all, required libraries are imported:

import RPi.GPIO as GPIO
import time

Then we configure GPIO pins we are going to use. We’ll use BCM GPIO naming. Please refer to Raspberry PI Pinout for more info.

No need to set Vcc and Ground, so only trigger pin (output) and echo pin (input) will be used:

echoPIN = 15
triggerPIN = 14

“Distance()” function makes all the work. After setting defaults to 0 for distance and duration variables. it triggers from triggerPIN to send ultrasonic signal:

GPIO.output(triggerPIN, 0)
GPIO.output(triggerPIN, 1) # here the trigger is put on
time.sleep(0.000010) # 10us of trigger duration
GPIO.output(triggerPIN, 0) # now trigger is put off
time.sleep(0.000002) # this time delay to avoid interference between trigger and echo

As described in timing diagram, we must measure feedback duration to calculate distance. So we set a “startT” time variable when echo goes to high and a “feedbackT” time variable when echo goes back to low. While cycles with “pass” does nothing but waiting that conditions change:

while GPIO.input(echoPIN) == 0: pass
startT = time.time()
while GPIO.input(echoPIN) == 1: pass
feedbackT = time.time()

Distance is calculated based on feedback duration as already explained. A small “if” check is done to avoid possible strange conditions. This can be used in future for addictional checks on failures.

if feedbackT == startT:
 distance = "N/A"
 duration = feedbackT - startT
 soundSpeed = 34300 # cm/s
 distance = duration * soundSpeed / 2
 distance = round(distance, 1)

Finally, “distance()” function returns distance above calculated as result:

return distance

Going to main loop, the simple print command is enriched to write results always on same terminal line:

 print (" Distance: " + str(distance())+ " ", end='\r')

User can terminate this script by pressing CTRL+C. This prints a courtesy message of “interrupted!” and cleans GPIO status:

except KeyboardInterrupt:


How useful was this post?

Click on a star to rate it anonymously!

Average rating 5 / 5. Vote count: 1

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?