0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Use Ultrasonic Sensor with Raspberry Pi: Simple Guide

To use an ultrasonic sensor with a Raspberry Pi, connect the sensor's trigger and echo pins to the Pi's GPIO pins, then write a Python script to send a pulse and measure the echo time. This time is converted to distance by calculating how long the sound wave took to bounce back.
📐

Syntax

Here is the basic Python syntax to use an ultrasonic sensor with Raspberry Pi's GPIO pins:

  • GPIO.setup(pin, GPIO.OUT): Set the trigger pin as output.
  • GPIO.setup(pin, GPIO.IN): Set the echo pin as input.
  • GPIO.output(trigger_pin, True/False): Send a pulse to start measurement.
  • GPIO.input(echo_pin): Read the echo pin to detect pulse return.
  • Calculate distance using the time difference between sending and receiving the pulse.
python
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()
💻

Example

This example shows how to measure distance using an HC-SR04 ultrasonic sensor connected to Raspberry Pi GPIO pins 23 (trigger) and 24 (echo). It sends a short pulse, waits for the echo, calculates the distance, and prints it.

python
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)

try:
    while True:
        GPIO.output(TRIG, False)
        time.sleep(0.5)

        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")

except KeyboardInterrupt:
    print("Measurement stopped by user")
    GPIO.cleanup()
Output
Distance: 15.23 cm Distance: 15.10 cm Distance: 15.05 cm ... (repeats every 0.5 seconds)
⚠️

Common Pitfalls

  • Incorrect GPIO pin numbering: Use BCM mode consistently to avoid confusion.
  • Not waiting for sensor to settle: Always wait 2 seconds after setup before measuring.
  • Timing errors: Make sure to measure pulse start and end correctly to avoid wrong distances.
  • Not cleaning up GPIO: Always call GPIO.cleanup() to reset pins.
  • Wiring mistakes: Connect trigger to output pin and echo to input pin properly; wrong wiring causes no readings.
python
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

TRIG = 23
ECHO = 24

# Wrong: Setting echo as output (should be input)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)  # Mistake fixed here

# Correct way:
# GPIO.setup(ECHO, GPIO.IN)

GPIO.cleanup()
📊

Quick Reference

Ultrasonic Sensor Pins:

  • VCC: 5V power
  • GND: Ground
  • Trig: Trigger pin (output from Pi)
  • Echo: Echo pin (input to Pi)

Distance Calculation: Distance (cm) = (Time (seconds) × 34300) / 2 = Time × 17150

GPIO Setup: Use GPIO.setmode(GPIO.BCM) and set trigger as output, echo as input.

Key Takeaways

Connect the ultrasonic sensor's trigger to a GPIO output pin and echo to a GPIO input pin on Raspberry Pi.
Send a short 10 microsecond pulse on the trigger pin to start measurement.
Measure the time the echo pin stays high to calculate distance using speed of sound.
Always wait 2 seconds after setup before measuring to let the sensor settle.
Clean up GPIO pins after use to avoid conflicts in future runs.