---
title: Step-by-step Guide: Building a Low-cost Ultrasonic Distance Sensor for Raspberry Pi
siteUrl: https://logzly.com/sensorcraft
author: sensorcraft (SensorCraft)
date: 2026-06-16T15:22:25.083161
tags: [ultrasonic, raspberrypi, diy]
url: https://logzly.com/sensorcraft/step-by-step-guide-building-a-low-cost-ultrasonic-distance-sensor-for-raspberry-pi
---


**Disclosure: We are reader supported, and earn affiliate commissions when you buy through us.**


Ever tried to measure the distance to a [coffee mug](https://www.amazon.com/s?k=coffee+mug&tag=organizationtip101-20) on your desk and got nothing but guesswork? A cheap ultrasonic sensor can turn that guess into a precise number, and you can hook it up to a [Raspberry Pi](https://www.amazon.com/s?k=Raspberry+Pi&tag=organizationtip101-20) in under an hour. I first tried this for a garage‑door‑open‑alert project, and the moment the Pi shouted “2.3 meters” I knew I had to share the recipe. Below is the exact path I followed, with the little tricks that saved me time and money.

## What You Need (and Why It’s Cheap)

| Item | Typical Cost | Reason |
|------|--------------|--------|
| [HC‑SR04 ultrasonic module](/sensorcraft/how-to-build-a-reliable-proximity-detector-for-home-iot-with-the-hcsr04) | $2‑3 | The workhorse that sends and receives sound bursts |
| Raspberry Pi (any model with GPIO) | $5‑10 for a Zero W | Provides the [processing power](https://www.amazon.com/s?k=processing+power&tag=organizationtip101-20) |
| Breadboard + jumper wires | $2‑4 | Makes wiring painless and reusable |
| 5 V [power supply](https://www.amazon.com/s?k=power+supply&tag=organizationtip101-20) for Pi | – | Already in most kits |
| Optional: 0.1 µF capacitor | $0.10 | Tames the noisy power line |

All of these parts are available from online hobby stores or local electronics markets. The total bill stays well under $15, which is why I call it low‑cost.

## Understanding the HC‑SR04

The [HC‑SR04](/sensorcraft/how-to-build-a-reliable-ultrasonic-proximity-sensor-for-home-automation-a-stepbystep-guide) works like a tiny bat. It sends a 40 kHz sound pulse (the **Trig** pin) and then listens for the echo (the **Echo** pin). The time it takes for the echo to return is proportional to the distance. The formula is simple:

```
distance (cm) = (echo_time µs) / 58
```

Why 58? Sound travels at roughly 340 m/s, which works out to 58 µs per centimeter for the round‑trip. No need to memorize the physics; the code will handle it.

## Wiring the Sensor to the Pi

### 1. Power Connections

- Connect **VCC** on the HC‑SR04 to the Pi’s 5 V pin (pin 2 or 4).
- Connect **GND** to any ground pin (pin 6, 9, 14, 20, 25, 30, 34, 39).

### 2. Signal Pins

- **Trig** goes to GPIO 23 (physical pin 16). You can pick another pin, just adjust the code.
- **Echo** goes to GPIO 24 (physical pin 18). The Echo line swings up to 5 V, which the Pi’s 3.3 V GPIO cannot tolerate directly. Use a simple voltage divider: two resistors, 1 kΩ and 2 kΩ, in series between Echo and ground. Tap the junction and feed that to GPIO 24. This drops the voltage to about 3.3 V.

### 3. Optional Smoothing

If you notice erratic readings, solder a 0.1 µF capacitor across VCC and GND on the sensor. It smooths out the supply spikes caused by the Pi’s [USB devices](https://www.amazon.com/s?k=USB+devices&tag=organizationtip101-20).

## The Software Part

### Installing the Libraries

Open a terminal on your Pi and run:

```
sudo apt update
sudo apt install python3-pip
pip3 install RPi.GPIO
```

`RPi.GPIO` is the standard library for accessing the Pi’s pins from Python.

### The Python Script

Create a file called `ultrasonic.py` and paste the following:

```python
import RPi.GPIO as GPIO
import time

# Pin definitions
TRIG = 23
ECHO = 24

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

def measure():
    # Send a 10 µs pulse to trigger
    GPIO.output(TRIG, False)
    time.sleep(0.05)          # settle
    GPIO.output(TRIG, True)
    time.sleep(0.00001)       # 10 µs
    GPIO.output(TRIG, False)

    # Wait for echo start
    while GPIO.input(ECHO) == 0:
        start = time.time()

    # Wait for echo end
    while GPIO.input(ECHO) == 1:
        end = time.time()

    # Compute distance
    elapsed = end - start
    distance_cm = (elapsed * 34300) / 2   # speed of sound 34300 cm/s
    return distance_cm

try:
    while True:
        dist = measure()
        print(f"Distance: {dist:.1f} cm")
        time.sleep(1)
except KeyboardInterrupt:
    print("\nStopped")
finally:
    GPIO.cleanup()
```

A few notes:

- The `time.sleep(0.05)` gives the sensor a moment to settle after power‑up.
- The `while` loops wait for the echo line to change state. In a noisy environment you might add a timeout to avoid hanging forever.
- The speed of sound is set to 343 m/s (or 34 300 cm/s). If you work in a very hot or cold room, you can tweak that number, but for most indoor projects the default is fine.

Run it with `python3 ultrasonic.py`. You should see a steady stream of distance values. Point the sensor at a wall, move your hand, and watch the numbers change.

## Debugging Tips From My Workshop

1. **No readings at all?** Double‑check the voltage divider on Echo. A common mistake is swapping the resistor positions, which leaves the pin at 5 V and trips the Pi’s protection.
2. **Fluctuating numbers** – Make sure the sensor isn’t picking up reflections from nearby objects. A small piece of foam taped behind the sensor can dampen stray echoes.
3. **Too slow** – The HC‑SR04 can only handle one measurement every ~60 ms. If you need faster updates, consider the newer MB‑1010 LV-MaxSonar, but that bumps the price up.

## Extending the Project

Now that you have a reliable distance reading, the sky’s the limit:

- **[Parking assistant](/sensorcraft/how-to-build-a-reliable-ultrasonic-proximity-sensor-for-home-automation-a-stepbystep-guide)**: Mount the sensor on a [bike rack](https://www.amazon.com/s?k=bike+rack&tag=organizationtip101-20) and use the Pi to flash an LED when a car gets too close.
- **Water level monitor**: Place the sensor above a tank and log the level to a [cloud service](https://www.amazon.com/s?k=cloud+service&tag=organizationtip101-20).
- **Smart [trash can](https://www.amazon.com/s?k=trash+can&tag=organizationtip101-20)**: Detect when the bin is full and send a notification to your phone.

All of these ideas reuse the same wiring and code, only the logic after the `measure()` call changes.

## Wrapping Up

Building a low‑cost ultrasonic distance sensor for a Raspberry Pi is a perfect entry point for anyone who wants to blend hardware with a bit of Python. The parts are cheap, the wiring is straightforward, and the code fits on a single page. Most importantly, you get instant, tangible feedback – something that keeps the hobby alive.

Give it a try, tinker with the parameters, and let the sensor become the eyes of your next [DIY project](https://www.amazon.com/s?k=DIY+project&tag=organizationtip101-20). Happy hacking!
