Week 10: Ultrasonic Sensor

For many (outdoor) projects a distance measurement is necessary or advantageous. These small modules are available starting at 1-2 bucks and can measure the distance up to 4-5 meters by ultrasound and are surprisingly accurate. 
This worksheet shows the connection and control.
Hardware
⦁ HC-SR04 Module
⦁ Resistors: 330Ω and 470Ω
⦁ Jumper wire
Wiring
There are four pins on the ultrasound module that are connected to the Raspberry:
⦁ VCC to Pin 2 (VCC)
⦁ GND to Pin 6 (GND)
⦁ TRIG to Pin 12
⦁ connect the 330Ω resistor to ECHO.  On its end you connect it to Pin 18 and through a 470Ω resistor you connect it also to Pin6 (GND).
We do this because the GPIO pins only tolerate maximal 3.3V. The connection to GND is to have an obvious signal on Pin 18. If no pulse is sent, the signal is 0 (through the connection with GND), else it is 1. If there would be no connection to GND, the input would be undefined if no signal is sent (randomly 0 or 1), so ambiguous.

Circuit diagram:

Program
First of all, the Python GPIO library should be installed

#Libraries import RPi.GPIO as GPIO
import time
 

#GPIO Mode (BOARD / BCM) GPIO.setmode(GPIO.BOARD)
 

#set GPIO Pins GPIO_TRIGGER = 12
GPIO_ECHO = 18
 

#set GPIO direction (IN / OUT) GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
 
def distance():
    # set Trigger to HIGH
    GPIO.output(GPIO_TRIGGER, True)
 
    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)
 
    StartTime = time.time()
    StopTime = time.time()
 
    # save StartTime
    while GPIO.input(GPIO_ECHO) == 0:
        StartTime = time.time()
 
    # save time of arrival
    while GPIO.input(GPIO_ECHO) == 1:
        StopTime = time.time()
 
    # time difference between start and arrival
    TimeElapsed = StopTime – StartTime
    # multiply with the sonic speed (34300 cm/s)
    # and divide by 2, because there and back
    distance = (TimeElapsed * 34300) / 2
 
    return distance
 
if _name_ == ‘_main_’:
    try:
        while True:
            dist = distance()
            print (“Measured Distance = %.1f cm” % dist)
            time.sleep(1)
 
        # Reset by pressing CTRL + C
    except KeyboardInterrupt:
        print(“Measurement stopped by User”)
        GPIO.cleanup()
So every second, the distance will be measured until the script is cancelled by pressing CTRL + C.
That‘s it. You can use it many fields, but who still want to measure larger distances would have to rely on laser measuring devices, which, however, are much more expensive.