How to measure distance with a Raspberry Pi?

Introduction

The distance sensor (also called an ultrasonic sensor) allows you to measure distance.
It can estimate distances ranging from 2 cm to 400 cm with an accuracy of 3 mm.
It is the most commonly used and cheapest distance sensor available.
There are much more precise sensors, but they are also much more expensive.

You can purchase one here or find it included in this kit.

In this lesson, we will see how to measure distance using a Raspberry Pi.
Here is the wiring diagram for connecting the HC-SR04 sensor to the Raspberry Pi:

Here is the Python program that reads the distance measurement.
To add it, you need to create a new file like this:

sudo nano distance.py
import RPi.GPIO as GPIO
import time

# Define pins
TRIG_PIN = 11
ECHO_PIN = 13

# Initialize the GPIO library
GPIO.setmode(GPIO.BOARD)
GPIO.setup(TRIG_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)

def distance():
    # Send ultrasonic pulse
    GPIO.output(TRIG_PIN, GPIO.LOW)
    time.sleep(2)  # Wait for sensor stabilization
    GPIO.output(TRIG_PIN, GPIO.HIGH)
    time.sleep(0.00001)
    GPIO.output(TRIG_PIN, GPIO.LOW)

    # Measure the time between sending and receiving the signal
    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

    # Calculate distance using speed of sound (343 m/s)
    distance_cm = pulse_duration * 34300 / 2

    return distance_cm

try:
    while True:
        dist = distance()
        print(f"Distance: {dist:.2f} cm")
        time.sleep(1)

except KeyboardInterrupt:
    # Clean up properly when Ctrl+C is pressed
    GPIO.cleanup()

To run the program, you can type the following command:

sudo python distance.py

You can see the distance measured by the sensor to an object in the Raspberry Pi terminal: