Difference between revisions of "Ultrasonic Sensor"
Jump to navigation
Jump to search
Line 1: | Line 1: | ||
+ | see also https://tutorials-raspberrypi.de/entfernung-messen-mit-ultraschallsensor-hc-sr04/ | ||
+ | |||
https://www.einplatinencomputer.com/wp-content/uploads/2016/02/hc-sr04_Steckplatine-762x1024.jpg | https://www.einplatinencomputer.com/wp-content/uploads/2016/02/hc-sr04_Steckplatine-762x1024.jpg | ||
Revision as of 19:45, 11 June 2019
see also https://tutorials-raspberrypi.de/entfernung-messen-mit-ultraschallsensor-hc-sr04/
# 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 InitTime-TriggerTime > 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 ("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()