import RPi.GPIO as GPIO import time led = 25 GPIO.setmode(GPIO.BCM) GPIO_TRIGGER = 5 GPIO_ECHO = 6 GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) GPIO.setup(led,GPIO.OUT) GPIO.output(led,GPIO.LOW) 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 print "CTRL+C = STOP program" if __name__ == '__main__': try: while True: dist = distance() print ("Distance = %.1f cm" % dist) time.sleep(0.1) if dist < 7: GPIO.output(led,GPIO.HIGH) else: GPIO.output(led,GPIO.LOW) except KeyboardInterrupt: GPIO.cleanup() # must be executed before program stop