Sensors: Ultasonic Sensors
Ultrasonic Sensors
The ultrasonic sensor is used to measure distances by using sound waves. The distance is measured based on the time it takes for the pulse to reach the object and comes back. Since the sensor uses sound waves, then the distance is equal to the speed of the sound waves multiplied by the time needed for the pulse to reach the object and comes back divided by two:
Distance = speed of sound * Time / 2
Speed of sound is 34300 cm/s; and time in seconds
So Distance (cm) = 17150 * Time(s)
How to Connect the Sensor?
The ultrasonic sensor has 4 pins: VC, Trig, Echo, and Gnd.
GND connected to the ground (Gnd) pin of the RPi;
Vcc connected to the 5V pin of the RPi;
ECHO (pulse output) connected to a RPi GPIO pin;
TRIG (or trigger: pulse input) connected to a RPi GPIO pin.
In this example (Figure 28):
The Vcc pin is connected to the pin# 2 (5V); Trig to pin# 16 (GPIO 23) ;
Echo to pin# 18 (GPIO 24); and Gnd to pin# 6.
Two resistors are needed on the circuit. R1=330Ω and R2=470Ω .
The wiring of the Raspberry Pi to the breadboard, resistors, and the sensor is show in the figure below:
Figure 29. shows the connection of the ultrasonic sensor to the Raspberry Pi.
The sensor can be used to trigger other loads on the RPi or can be used to measure distance.
Python program to measure distance:
import RPi.GPIO as GPIO
import time
#TRIG = 10
#ECHO = 8
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(10, GPIO.OUT)
GPIO.setup(8, GPIO.IN)
while True:
GPIO.output(10, False)
time.sleep(0.3)
GPIO.output(10, True)
time.sleep(0.001)
GPIO.output(10, False)
while GPIO.input(8)==0:
signalOff=time.time()
while GPIO.input(8)==1:
signalOn=time.time()
timePassed=signalOn-signalOff
distance=timePassed*17150
print distance,”cm”
GPIO.cleanup()

