PiDojo : Ultrasonic Range Sensor with the Raspberry Pi

The HC-SR04 Ultrasonic Module Distance Sensor is a cheap sensor that can be used to measure the distance between itself and an object in front of it by sending an ultrasonic pulse and listening for its echo. It can be connected to many things including the Raspberry Pi.

The HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 Ultrasonic Distance Sensor

We connected up our sensor and used the following code to take a measurement.

 

</pre>
#!/usr/bin/python3

import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

GPIO_TRIGGER = 10
GPIO_ECHO = 9

print ("Ultrasonic Measurement")

GPIO.setup(GPIO_TRIGGER,GPIO.OUT)
GPIO.setup(GPIO_ECHO,GPIO.IN)

GPIO.output(GPIO_TRIGGER,False)

time.sleep(0.5)

GPIO.output(GPIO_TRIGGER,True)
time.sleep(0.001)
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()

elapsed = stop - start

distance = elapsed * 34000

distance = distance / 2

print ('distance = ', distance)

GPIO.cleanup()

 

We then combined our sensor with our 7-Segment displays from last week.
Here are my slides ultrasonic measurement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s