Ultrasonic Distance Sensor (HC-SR04)

We can use the Ultrasonic Distance Sensor (HC-SR04) to measure distances up to about a meter. The sensor is not that accurate so if ultra precision is needed then perhaps some sort of laser measuring system would be more appropriate, however for most applications a high level of accuracy is not required and the relative simplicity of the HC-SR04 makes it an excellent choice for most projects.

The HC-SR04 Ultrasonic Distance Sensor (Front and Back)

Wiring The Sensor

The only thing we need to be careful about is that we need a resistor (1kΩ) wired in series to the Echo pin to protect the Raspberry Pi GPIO pin that it connects to as the voltage can be too high from it otherwise and this might damage the pins on the Pi. The following table gives us the pin wirings for the device.
HC-SR04 Pin Raspbrry Pi Pin
VCC +5v
GND Ground (GND)
Pinout table for the HC-SR04 distance sensor

The Code

Now we need to create a small pulse which we do by making the Trigger pin go high for a very short period of time (1μs) and then pull it low again. This creates a pulse inaudible to the human ear. This pulse travels forward and hits an object or surface and then bounces back. When it bounces back to the sensor's inputs it creates a high signal on the Echo channel. We listen for this signal and then divide the returned value by 2 (it's travelled to the object and back, twice the distance) and then calculate the distance based on the speed of sound in air (a known speed, 343 m/s).
import time
import RPi.GPIO as GPIO


TRIG = 23
ECHO = 24


GPIO.output(TRIG, False)
print(“Letting sensor settle”)

GPIO.output(TRIG, True)
GPIO.output(TRIG, False)

while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()

pulse_dur = pulse_end - pulse_start
distance = pulse_dur * 17150
distance = round(distance, 2)
print(str(distance) + “ cm”)
Try running the code and holding a piece of paper (or your hand) in front of the sensor.