Raspberry Pi Program to Use Ultrasonic Sensor for Distance
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
How to Think About It
Algorithm
Code
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()
Dry Run
Let's trace measuring distance when an object is 15 cm away.
Trigger pulse sent
GPIO.output(TRIG, True) for 10 microseconds triggers sensor.
Echo pin goes HIGH
pulse_start = 1697050000.123456 (time when echo pin rises)
Echo pin goes LOW
pulse_end = 1697050000.124344 (time when echo pin falls)
Calculate pulse duration
pulse_duration = pulse_end - pulse_start = 0.000888 seconds
Calculate distance
distance = 0.000888 * 17150 = 15.22 cm
| Step | Pulse Duration (s) | Distance (cm) |
|---|---|---|
| 1 | N/A | N/A |
| 2 | N/A | N/A |
| 3 | 0.000888 | 15.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
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)
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()
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| RPi.GPIO basic | O(1) | O(1) | Simple projects, direct control |
| gpiozero library | O(1) | O(1) | Ease of use, beginners |
| pigpio library | O(1) | O(1) | High precision timing |
GPIO.cleanup() can cause errors on rerun.