HC-SR04 Ultrasonic Range Finder
The HC-SR04 ultrasonic range finder is very simple and cheap to use. Unlike Arduino Uno R3 operated by 5V, Raspberry Pi reads 3.3V signal so the 5V output of the HC-SR04 needs to be converted from 5V to 3.3V.
There are some useful breakout board converting higher voltage to lower voltage but voltage dividers can adjust the voltage level easily by using the simple arithmetic calculation.
In this tutorial, 1K ohm [ Brown-Black-Red] and 2K [Red-Black-Red] resistors are used to convert the 5V to 3.3V.
WIRING
Wiring four ultrasonic range finders with Raspberry Pi is not easy so we recommend to use cobbler cables to extend the 40pin GPIO to the breadboard or to adopt the protoshield. Basically, VCC (5V) signals are all 'red' colors while GND signals are all 'black' colors.
The following code are written in Raspberry Pi. You can write and program the code either in Python IDLE or in the command windows.
To write down the code in the script, I used nano editor but you can use vim or other editor.
$ nano ultrasonic.py
It will allow you to write a script in the editor and save with Ctrl+X.
Once it is saved, you can execute the code by using the following command
$ python ultrasonic.py
Super Easy!
Python code
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
TRIG = [4,17,18,27]
ECHO = [10,9,11,8]
distance = [2000,2000,2000,2000]
pulse_start = [0,0,0,0]
pulse_end = [0,0,0,0]
pulse_duration = [0,0,0,0]
for i in range(len(ECHO))
GPIO.setup(TRIG[i],GPIO.OUT)
GPIO.setup(ECHO[i],GPIO.IN)
try:
while True:
for i in range(len(ECHO)):
GPIO.output(TRIG[i],False)
time.sleep(0.5)
GPIO.output(TRIG[i],True)
time.sleep(0.00001)
GPIO.output(TRIG[i],False)
while GPIO.input(ECHO[i])==0:
pulse_start[i]==time.time()
while GPIO.input(ECHO[i])==1:
pulse_end[i]==time.time()
pulse_duration[i]=pulse_end[i]-pulse_start[i]
distance[i]=pulse_duration[i]*17150
distance[i]=round(distance[i],2)
print "Distance:",distance,"cm"
except:
GPIO.cleanup()