import threading import RPi.GPIO as GPIO import time #GPIO Mode (BOARD / BCM) GPIO.setmode(GPIO.BCM) class Sensor(threading.Thread): """ultrasonic sensor continous distance reading at given interval in seconds""" def __init__(self,interval, gpio_trig, gpio_echo): super(Sensor, self).__init__() self.inter = interval self.trig = gpio_trig self.echo = gpio_echo #set GPIO pins direction (IN / OUT) GPIO.setup(self.trig, GPIO.OUT) GPIO.setup(self.echo, GPIO.IN) self.dist = 0 self.terminated = False self.start() def run(self): while not self.terminated: # set Trigger to HIGH GPIO.output(self.trig, True) # set Trigger to LOW after 0.01ms time.sleep(0.00001) GPIO.output(self.trig, False) StartTime = time.time() StopTime = time.time() # save StartTime while GPIO.input(self.echo) == 0: StartTime = time.time() # save time of arrival while GPIO.input(self.echo) == 1: StopTime = time.time() # time difference between start and arrival TimeElapsed = StopTime - StartTime # multiply by sonic speed (34300 cm/s) # and divide by 2, because there and back self.dist = (TimeElapsed * 34300) / 2 time.sleep(self.inter) #Sensor object initiated with GPIO programmable pins 23 and 24 SensorA = Sensor(interval=.7, gpio_trig=23, gpio_echo=24) try: while True: print("Measured Distance = %.1f cm" % SensorA.dist) except KeyboardInterrupt: SensorA.terminated = True GPIO.cleanup()