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 ( and there is another excellent example with code at (

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


GPIO_ECHO = 22        #GPIO_25

#Set Pins as output and input

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

#Allow module to settle

def sonar(n):
    #Send 10us pulse to trigger
    GPIO.output(GPIO_TRIGGER, True)
    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:

    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