Oct-29-2021, 02:17 PM
The first thing that jumps out at me is that there is a lot of duplication in the functions distance and distance2 of which the names also give it away.
The only things that differ between them are trigger and echo so these can be passed into a single function.
The only things that differ between them are trigger and echo so these can be passed into a single function.
def get_distance(trigger, echo): # set Trigger to HIGH GPIO.output(trigger, True) # set Trigger after 0.01ms to LOW time.sleep(0.00001) GPIO.output(trigger, False) StartTime = time.time() StopTime = time.time() # save StartTime while GPIO.input(echo) == 0: StartTime = time.time() # save time of arrival while GPIO.input(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 * 17150) return distancethen call it as follows
distance1 = get_distance(GPIO_TRIGGER, GPIO_ECHO) distance2 = get_distance(GPIO2_TRIGGER, GPIO2_ECHO)