Introduction

Ever wanted your Raspberry Pi to sense the distance to nearby objects, like a proximity alarm or parking assistant? This tutorial shows you how to connect and use an HC-SR04 ultrasonic sensor with Raspberry Pi using Python.

By the end of this guide, you’ll be able to measure distance in real-time with just a few lines of code.
What You’ll Need

  • Raspberry Pi (with GPIO pins)

  • HC-SR04 ultrasonic sensor

  • Breadboard and jumper wires

  • 1 × resistor 330Ω (optional)

  • 1 × resistor 470Ω (optional)

  • Python 3 installed (default on Raspberry Pi OS)

 Tip: You may need a voltage divider to drop 5V from HC-SR04’s Echo pin to 3.3V compatible with Raspberry Pi.

Wiring the HC-SR04 to Raspberry Pi

HC-SR04 PinConnect to Raspberry Pi
VCC5V (Pin 2)
GNDGND (Pin 6)
TRIGGPIO23 (Pin 16)
ECHOGPIO24 (Pin 18)

 

Python Code to Read Distance

Here’s a simple Python script to read distance from the ultrasonic sensor:

import RPi.GPIO as GPIO
import time

# Setup
TRIG = 23
ECHO = 24

GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

print("Measuring distance...")

try:
    while True:
        GPIO.output(TRIG, False)
        time.sleep(0.5)

        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 * 17150  # cm
        distance = round(distance, 2)

        print(f"Distance: {distance} cm")

except KeyboardInterrupt:
    print("\nMeasurement stopped by user")
    GPIO.cleanup()

How the Code Works

  • TRIG pin sends a 10µs pulse to start the ultrasonic burst.

  • ECHO pin receives the pulse reflected back from an object.

  • The time taken for the pulse to return is used to calculate distance using the speed of sound.

Expected Outcome

Once the script runs, your terminal will display real-time distance readings like:
 

Distance: 12.34 cm
Distance: 13.01 cm
Distance: 11.95 cm

This setup is useful for:

  • Obstacle detection

  • Level sensors

  • DIY parking systems

  • Motion-triggered alerts


Troubleshooting and Tips

  • 🛠️ Readings are stuck at 0 or very high? Double-check your wiring, especially TRIG/ECHO pins.

  • 🔋 Sensor not responding? Make sure you’re powering it via 5V and reducing the 5V ECHO output using a resistor divider.

Conclusion

You’ve just turned your Raspberry Pi into a distance-measuring device using an HC-SR04 sensor and Python. This project forms the base for smart robotics, automation systems, and interactive installations.