Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import RPi.GPIO as GPIO
import time
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
#set GPIO Pins for Ultasonic Senor1 (Front Face)
gpioTrigger1 = 4
gpioEcho1 = 17
#set GPIO Pins for Ultasonic Senor2 (Left Face)
gpioTrigger2 = 26
gpioEcho2 = 19
#setting GPIO direction (IN / OUT) for Sensor1 (Front Face)
GPIO.setup(gpioTrigger1, GPIO.OUT)
GPIO.setup(gpioEcho1, GPIO.IN)
#setting GPIO direction (IN / OUT) for Sensor2 (Left Face)
GPIO.setup(gpioTrigger2, GPIO.OUT)
GPIO.setup(gpioEcho2, GPIO.IN)
def distanceBySensor1():
# setting Trigger to HIGH for Ultrasonic Sensor1 (Front Face)
GPIO.output(gpioTrigger1, True)
# setting Trigger of Ultrasonic Sensor1 (Front Face) after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(gpioTrigger1, False)
startTimeSensor1 = time.time()
stopTimeSensor1 = time.time()
# save StartTime
while GPIO.input(gpioEcho1) == 0:
startTimeSensor1 = time.time()
# save time of arrival
while GPIO.input(gpioEcho1) == 1:
stopTimeSensor1 = time.time()
# time difference between start and arrival
timeElapsedSensor1 = stopTimeSensor1 - startTimeSensor1
# multiplying with the sonic speed (34300 cm/s)
# and dividing by 2, because there and back
distanceBySensor1 = (timeElapsedSensor1 * 34300) / 2
return distanceBySensor1
def distanceBySensor2():
# setting Trigger to HIGH for Ultrasonic Sensor1 (Front Face)
GPIO.output(gpioTrigger2, True)
# setting Trigger of Ultrasonic Sensor1 (Front Face) after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(gpioTrigger2, False)
startTimeSensor2 = time.time()
stopTimeSensor2 = time.time()
# save StartTime
while GPIO.input(gpioEcho2) == 0:
startTimeSensor2 = time.time()
# save time of arrival
while GPIO.input(gpioEcho2) == 1:
stopTimeSensor2 = time.time()
# time difference between start and arrival
timeElapsedSensor2 = stopTimeSensor2 - startTimeSensor2
# multiplying with the sonic speed (34300 cm/s)
# and dividing by 2, because there and back
distanceBySensor2 = (timeElapsedSensor2 * 34300) / 2
return distanceBySensor2
if __name__ == '__main__':
try:
while True:
distanceCalculatedBySensor1 = distanceBySensor1()
print ("Measured Distance = %.1f cm" % distanceCalculatedBySensor1)
time.sleep(1)
distanceCalculatedBySensor2 = distanceBySensor2()
print ("Measured Distance = %.1f cm" % distanceCalculatedBySensor2)
time.sleep(1)
except KeyboardInterrupt:
print("Measurement stopped by User")
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment