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.
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
