We use an ultrasonic DistanceSensor to measure how far away something is without touching it. It sends sound waves and listens for echoes to find the distance.
0
0
DistanceSensor (ultrasonic) in Raspberry Pi
Introduction
To check if an object is close or far, like a parking sensor in a car.
To measure the water level in a tank without opening it.
To detect if someone is near a door to open it automatically.
To avoid obstacles for a small robot moving around.
Syntax
Raspberry Pi
from gpiozero import DistanceSensor sensor = DistanceSensor(echo=17, trigger=4) distance = sensor.distance # distance in meters
The echo pin listens for the sound wave bounce back.
The trigger pin sends the sound wave.
Examples
This sets up the sensor with echo on pin 18 and trigger on pin 23, then prints the distance in meters.
Raspberry Pi
from gpiozero import DistanceSensor sensor = DistanceSensor(echo=18, trigger=23) print(sensor.distance)
This example continuously prints the distance in centimeters with one decimal place.
Raspberry Pi
from gpiozero import DistanceSensor sensor = DistanceSensor(echo=24, trigger=25) while True: print(f"Distance: {sensor.distance * 100:.1f} cm")
Sample Program
This program measures the distance five times, printing it in centimeters with two decimals, pausing one second between each measurement.
Raspberry Pi
from gpiozero import DistanceSensor import time sensor = DistanceSensor(echo=17, trigger=4) for _ in range(5): distance_meters = sensor.distance distance_cm = distance_meters * 100 print(f"Distance: {distance_cm:.2f} cm") time.sleep(1)
OutputSuccess
Important Notes
The distance value is a float representing meters.
Make sure the sensor pins match your Raspberry Pi wiring.
Keep the sensor away from soft surfaces that absorb sound, or readings may be inaccurate.
Summary
DistanceSensor uses sound waves to measure distance without touching.
Use echo and trigger pins to connect the sensor.
Distance is given in meters as a float, multiply by 100 for centimeters.