HC-SR04 ultrasonic distance sensor on Raspberry

HC-SR04 is a commonly used module for non contact distance measurement for distances from 2cm to 400cm. It uses sonar (like bats and dolphins) to measure distance with high accuracy and stable readings. It consist of an ultrasonic transmitter, receiver and control circuit. The transmitter transmits short bursts which gets reflected by target and are picked up by the receiver. The time difference between transmission and reception of ultrasonic signals is calculated and as a result you get the distance.

This tutorial shows the connection and how to control the sensor.

What do you need?

  • HC-SR04 sensor
  • 1kΩ resistor
  • Jumper wire
  • Raspberry Pi

Connecting the distance sensor

There are four pins on the ultrasound module that have to connect to the Raspberry:

  • VCC to Pin 2 (5V)
  • GND to Pin 6 (GND)
  • TRIG to Pin 16 (GPIO23)
  • ECHO to 1kΩ resistor, than connect the resistor to Pin 18 (GPIO24)

(The Trig Pin and the Echo Pin can be connect to other GPIO, these are the ones I used, but if you change the GPIO remember to change the script below)

Here is the structure as a circuit diagram:

Script for controlling

First of all, you should install the Python GPIO library, if you haven’t installed it check my guide on how to install GPIO library.

To use the module, open the terminal and create a new python script:

sudo nano dist.py

with the following content:

import RPi.GPIO as GPIO                  
import time                               

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)
TRIG = 23  
GPIO.setwarnings(False)
ECHO = 24

print "Measurement in progress"

GPIO.setup(TRIG,GPIO.OUT)                 
GPIO.setup(ECHO,GPIO.IN) 

GPIO.output(TRIG, False)                

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

if distance > 5 and distance < 400:     
         print "Distance:",distance - 0.5,"cm"
else:
         print "Out Of Range"

After that we run:

sudo python dist.py

Finally you can see the script print on the display the values misured by the sensor.

Certainly you can use it many fields, but who still want to measure larger distances would have torely on laser measuring devices which, however, are much more expensive.

Previous Entries Install PhpMyAdmin on Ubuntu Next Entries MySQL dynamic insertion by a python script