Wednesday, October 30, 2013

Using Sonar Sensor with the Raspberry PI

In this post I'm going to use the same Sonar sensor from the last blog post with the Raspberry PI and use python for measuring distance of objects. Just like interfacing with the Arduino you need to connect the Sensor to +5v and Gnd to the Raspberry PI. I'm using GPIO pins 24 and 25 to connect my sensor's trigger and echo pins. As a reference loook at the following image for the GPIO pinout of the PI.

The following code interfaces the sensor with the Raspberry PI. The original code can be found at (http://www.raspberrypi.org/phpBB3/viewtopic.php?f=37&t=40479) and there is another excellent example with code at (http://www.raspberrypi-spy.co.uk/2012/12/ultrasonic-distance-measurement-using-python-part-1/).


#Sonar interface with the Raspberry PI
 
#Import Python libraries
import time
import RPi.GPIO as GPIO


GPIO.setmode(GPIO.BOARD)

GPIO_TRIGGER = 18    #GPIO_24
GPIO_ECHO = 22        #GPIO_25

#Set Pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo

#Set Trigger low
GPIO.output(GPIO_TRIGGER, False)

#Allow module to settle
time.sleep(0.5)

def sonar(n):
    #Send 10us pulse to trigger
    GPIO.output(GPIO_TRIGGER, True)
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)
 
    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 traveled in that time is time
    #multiplied by the speed of sound (cm/s)
    distance = elapsed * 34000

    #That was the total distance so half it for reaching the object
    distance = distance /2

    return distance

while True:
    time.sleep(0.3)

    distance = sonar(0)
    print distance

   
Here are a few pictures of the work in progress. The arduino can be ignored. Its just sitting there on the breadboard from my previous experiment of interfacing the Sonar with it.





No comments:

Post a Comment