HC-SR04 Ultrasonic Sensor
The HC-SR04 measures distance using ultrasonic pulses. Range: 2 cm – 4 m, accuracy: ±3 mm.
Wiring (Raspberry Pi)
| HC-SR04 | Raspberry Pi |
|---|---|
| VCC | Pin 2 (5V) |
| GND | Pin 6 (GND) |
| TRIG | GPIO23 (Pin 16) |
| ECHO | GPIO24 via voltage divider (Pin 18) |
WARNING
ECHO outputs 5V. Use a voltage divider (1kΩ + 2kΩ) to bring it down to 3.3V before connecting to the Pi GPIO.
Python Code
python
import RPi.GPIO as GPIO
import time
TRIG = 23
ECHO = 24
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
def get_distance():
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()
duration = pulse_end - pulse_start
distance = duration * 17150 # cm
return round(distance, 2)
try:
while True:
print(f"Distance: {get_distance()} cm")
time.sleep(0.5)
finally:
GPIO.cleanup()