Please note that the source code is using GPIO 14/15 which is different from the wiring above ...
# WF 2019-06-11
# Distance Measuring with HC-SR04 Ultrasonic Sensor
#
# You need to modify the GPIO_TRIGGER and GPIO_ECHO settings
# according to your setup for this code to work properly.
# Needed Libraries
import RPi.GPIO as GPIO
import time
#GPIO Modus (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
#GPIO Pins to be used
GPIO_TRIGGER = 15
GPIO_ECHO = 14
# set direction of GPIO pins (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 to Low after 0.01ms
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
InitTime = time.time()
TriggerTime = time.time()
# Sound travels 6 m in 1/40 of a second the
# HC-SR04 can measure up to some 3m only so 6m is the maximum echo
# travel distance
MaxTime = 1/40.0;
EchoTime = time.time()
# wait for trigger and set time
while GPIO.input(GPIO_ECHO) == 0:
TriggerTime = time.time()
if TriggerTime-InitTime > MaxTime:
break;
# wait for echo and set time
while GPIO.input(GPIO_ECHO) == 1:
EchoTime = time.time()
if EchoTime-TriggerTime > MaxTime:
break;
# calc time difference between trigger and echo
TimeElapsed = EchoTime - TriggerTime
# multiply by speed fo sound (34300 cm/s)
# and divide by two (sound went back and forth)
distance = (TimeElapsed * 34300) / 2
return distance
if __name__ == '__main__':
try:
print("Starting ultrasound distance measurement ...")
while True:
dist = distance()
if dist <-300:
print ("GPIO_ECHO %d does not go low" %GPIO_ECHO)
else:
if dist <= 300:
print ("distance = %.1f cm" % dist)
else:
print ("distance = ?");
time.sleep(1)
# on CTRL-C reset GPIO
except KeyboardInterrupt:
print("Aborted ultrasound distance measurement by User ... cleaning up GPIO")
GPIO.cleanup()