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.
This is the pinout I used
|Raspberry Pi Pin||Module Pin|
The code is written in python
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) TRIGPIN = 23 ECHOPIN = 24 print "Distance Measurement In Progress" GPIO.setup(TRIGPIN,GPIO.OUT) GPIO.setup(ECHOPIN,GPIO.IN) GPIO.output(TRIGPIN, False) print "Delay for sensor stability" time.sleep(2) GPIO.output(TRIGPIN, True) time.sleep(0.00001) 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" GPIO.cleanup()
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