Home Code Raspberry Pi and HC-SR04 Ultrasonic Range Sensor

Raspberry Pi and HC-SR04 Ultrasonic Range Sensor

by shedboy71

The HC-SR04 Ultrasonic Range Sensor is used to measure distances by using ultrasonic sounds. It works by sending out a burst of ultrasound and listening for the echo when it bounces off of an object. A short pulse to trigger the detection, then listens for a pulse on the echo pin.



The duration of this second pulse is equal to the time taken by the ultrasound to travel to the object and back to the sensor. Using the speed of sound, this time can be converted to distance.


  • Input voltage: 5v
  • Current: Less than 2mA
  • Sensor angle: 15 degrees
  • Detection distance: 2cm-450cm
  • Accuracy: Up to 0.3cm
  • Input trigger signal: 10us TTL impulse
  • Echo signal : output TTL PWL signal


Now as you may see from the specs above the output is a 5v TTL signal, if this is directly placed on to a GPIO pin of your PI then this may damage it. You will need either a voltage divider to drop down to 3.3v, a level shifter or in my case I used a protected GPIO board from cyntech – http://shop.cyntech.co.uk/products/protected-gpio-extender. If you visit the site you’ll see that this offers protection to the GPIO pins.

Pi and HC-SR04_schem

Pi and HC-SR04_schem

This is the pinout I used

Raspberry Pi Pin Module Pin
2 Vcc
6 Gnd
16 Trig
18 Echo


The code is written in python

import RPi.GPIO as GPIO
import time
print "Distance Measurement In Progress"
GPIO.output(TRIGPIN, False)
print "Delay for sensor stability"
GPIO.output(TRIGPIN, True)
GPIO.output(TRIGPIN, False)
while GPIO.input(ECHOPIN)==0:
  start = time.time()
while GPIO.input(ECHOPIN)==1:
  end = time.time()
duration = end - start
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distance = duration * 34029
distance = distance / 2
distance = round(distance, 2)
print "Distance:",distance,"cm"



Here are my results, I placed objects on a cutting mat which had cm’s marked on it, as an example I placed an object 42cm away on the final reading, as you can see it read 42.84 which is pretty good

Pi and Ultrasonic sensor

Pi and Ultrasonic sensor



Ultrasonic Module HC-SR04 Distance Measuring Transducer Sensor

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More