0
0
Iot-protocolsProgramBeginner · 2 min read

Raspberry Pi Program to Use Ultrasonic Sensor for Distance

Use the RPi.GPIO library to control the ultrasonic sensor pins and measure distance by sending a trigger pulse with GPIO.output(trigger, True), then measure the echo pulse duration with GPIO.input(echo) to calculate distance.
📋

Examples

InputObject 10 cm away
OutputDistance: 10.0 cm
InputObject 50 cm away
OutputDistance: 50.0 cm
InputNo object detected (timeout)
OutputDistance: 0.0 cm
🧠

How to Think About It

To use an ultrasonic sensor with Raspberry Pi, first send a short pulse to the sensor's trigger pin to start measurement. Then listen on the echo pin to detect how long the pulse takes to return. This time is proportional to the distance of the object. Calculate distance by multiplying the time by the speed of sound and dividing by two.
📐

Algorithm

1
Set up GPIO pins for trigger (output) and echo (input).
2
Send a 10 microsecond pulse to the trigger pin.
3
Wait for the echo pin to go HIGH and record the start time.
4
Wait for the echo pin to go LOW and record the end time.
5
Calculate the pulse duration as end time minus start time.
6
Calculate distance using the formula: distance = pulse duration * 17150.
7
Print the distance in centimeters.
💻

Code

raspberry_pi
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24

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

GPIO.output(TRIG, False)
print("Waiting for sensor to settle")
time.sleep(2)

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

distance = round(distance, 2)

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

GPIO.cleanup()
Output
Waiting for sensor to settle Distance: 15.23 cm
🔍

Dry Run

Let's trace measuring distance when an object is 15 cm away.

1

Trigger pulse sent

GPIO.output(TRIG, True) for 10 microseconds triggers sensor.

2

Echo pin goes HIGH

pulse_start = 1697050000.123456 (time when echo pin rises)

3

Echo pin goes LOW

pulse_end = 1697050000.124344 (time when echo pin falls)

4

Calculate pulse duration

pulse_duration = pulse_end - pulse_start = 0.000888 seconds

5

Calculate distance

distance = 0.000888 * 17150 = 15.22 cm

StepPulse Duration (s)Distance (cm)
1N/AN/A
2N/AN/A
30.00088815.22
💡

Why This Works

Step 1: Triggering the sensor

Sending a short pulse to the trigger pin tells the sensor to send an ultrasonic burst.

Step 2: Measuring echo time

The echo pin goes HIGH when the burst is sent and LOW when it returns; measuring this time gives the round-trip duration.

Step 3: Calculating distance

Distance is half the round-trip time multiplied by the speed of sound (converted to cm).

🔄

Alternative Approaches

Using gpiozero library
raspberry_pi
from gpiozero import DistanceSensor
from time import sleep
sensor = DistanceSensor(echo=24, trigger=23)
while True:
    print(f"Distance: {sensor.distance * 100:.2f} cm")
    sleep(1)
gpiozero simplifies sensor handling but adds a dependency and less control.
Using pigpio library for more precise timing
raspberry_pi
import pigpio
import time
pi = pigpio.pi()
TRIG = 23
ECHO = 24
pi.set_mode(TRIG, pigpio.OUTPUT)
pi.set_mode(ECHO, pigpio.INPUT)
pi.write(TRIG, 0)
time.sleep(2)
pi.gpio_trigger(TRIG, 10)
while pi.read(ECHO) == 0:
    start = time.time()
while pi.read(ECHO) == 1:
    end = time.time()
pulse_duration = end - start
distance = pulse_duration * 17150
print(f"Distance: {distance:.2f} cm")
pi.stop()
pigpio offers more accurate timing but requires running pigpio daemon.

Complexity: O(1) time, O(1) space

Time Complexity

The program runs a fixed number of steps to measure distance once, so time is constant O(1).

Space Complexity

Only a few variables are used for timing and calculation, so space is constant O(1).

Which Approach is Fastest?

Using pigpio can be faster and more precise but requires extra setup; gpiozero is simpler but less flexible.

ApproachTimeSpaceBest For
RPi.GPIO basicO(1)O(1)Simple projects, direct control
gpiozero libraryO(1)O(1)Ease of use, beginners
pigpio libraryO(1)O(1)High precision timing
💡
Always wait 2 seconds after setting up the sensor before measuring to let it settle.
⚠️
Forgetting to clean up GPIO pins with GPIO.cleanup() can cause errors on rerun.