Tech details:

  • Working Voltage DC 5 V 
  • Working Current 15mA 
  • Working Frequency 40Hz
  • Max Range 4m 
  • Min Range 2cm
  • Measuring Angle 15 degree 
  • Trigger Input Signal 10uS TTL pulse 
  • Echo Output Signal Input TTL lever signal and the range in proportion 
  • Dimension 45*20*15mm 

Connectivity:

4 pin connector, pins as follows:

  • VCC: 5V Supply
  • TRIG: Trigger Pulse Input
  • ECHO: Echo Pulse Output (5v)
  • GND: 0V Ground

Echo Pulse Output requires Voltage to be stepped down to 3.3V to work with Raspberry and prevent damage.

What it does?

Sonar HC-SR04 sensor issues an ultrasonic pulse to determine a distance from the board itself. Sensors placement limits the min range to 2cm, and it is possible to detect objects as far as 400cm away (4m). Output is generated to the GPIO21 on the design below and the command to check for the distance is issued on GPIO2.

How to use it?Sonar HC-SR04 sensor breadboard

You will need 2 GPIO pins on your board to send and receive signals to the sensor (blue), board itself is powered by 5V from RPI (red) and last connections is for ground (black).

Sample code:

You can test the Sonar HC-SR04 sensor using a python2 code from here.

[code language=”python”]

#required libraries
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM) #Set GPIO pin numbering

TRIG = 2 #Assign PIN to TRIGGER
ECHO = 21 #Assign PIN to ECHO

print “Checking”

GPIO.setup(TRIG,GPIO.OUT) #Set pin as GPIO out
GPIO.setup(ECHO,GPIO.IN) #Set pin as GPIO in

while True:

GPIO.output(TRIG, False) #Set TRIG as LOW
print “Waitng For Sensor To Settle”
time.sleep(2) #Delay of 2 seconds

GPIO.output(TRIG, True) #Set TRIG as HIGH
time.sleep(0.00001) #Delay of 0.00001 seconds
GPIO.output(TRIG, False) #Set TRIG as LOW

while GPIO.input(ECHO)==0: #Check whether the ECHO is LOW
pulse_start = time.time() #Saves the last known time of LOW pulse

while GPIO.input(ECHO)==1: #Check whether the ECHO is HIGH
pulse_end = time.time() #Saves the last known time of HIGH pulse

pulse_duration = pulse_end – pulse_start #Get pulse duration to a variable

distance = pulse_duration * 17150 #Multiply pulse duration by 17150 to get distance
distance = round(distance, 2) #Round to two decimal points

if distance > 2 and distance < 400: #Check whether the distance is within range
print “Distance to your object:”,distance – 0.5,”cm” #Print distance with 0.5 cm calibration
else:
print “Out of range” #display out of range

[/code]
SHARE