import threading import RPi.GPIO as GPIO import time # The value used to hold the distance global distance distance = 0 #GPIO Mode (BOARD / BCM) GPIO.setmode(GPIO.BCM) #set GPIO Pins GPIO_TRIG = 23 GPIO_ECHO = 24 #set GPIO direction (IN / OUT) GPIO.setup(GPIO_TRIG, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) class Sensor(threading.Thread): def __init__(self,interval): self.inter = interval self.terminated = False self.start() def run(self): global distance while not self.terminated: # set Trigger to HIGH GPIO.output(GPIO_TRIG, True) # set Trigger to LOW after 0.01ms time.sleep(0.00001) GPIO.output(GPIO_TRIG, 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 by sonic speed (34300 cm/s) # and divide by 2, because there and back distance = (TimeElapsed * 34300) / 2 time.sleep(self.inter) SensorA = Sensor(1) # Example bit of code to read the value from the thread global distance try: while True: print("Measured Distance = %.1f cm" % distance) time.sleep(1) except KeyboardInterrupt: GPIO.cleanup() SensorA.terminated = True