UltraSonic Sensors

Ebay Kit
The Sensor is powered by a +5v rail from pin 2 of the Pi. The trigger pin comes from pin 16 (Gpio23) and this tell the sensor to start measuring. The echo pin in normally low until the sensor sends an output then it goes +5v for the time the sensor took to measure the distance. This is the reason for the resistors as the GPIO can only handle a +3.3v.

Diagram

The Code

#!/usr/bin/python
# Import required Python libraries
import time
import RPi.GPIO as GPIO
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
#
# Define GPIO to use on Pi
GPIO_TRIGGER = 23
GPIO_ECHO = 24
#
print "Ultrasonic Measurement"
#
# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo
#
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)
#
# Allow module to settle
time.sleep(0.5)
#
# Send 10us pulse to trigger
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
#
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
#
# Calculate pulse length
elapsed = stop-start
#
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distance = elapsed * 34000
#
# That was the distance there and back so halve the value
distance = distance / 2
#
print "Distance : %.1f" % distance
#
# Reset GPIO settings
GPIO.cleanup()

  
Tagged , . Bookmark the permalink.

Comments are closed.