Untitled

 avatar
user_2252848675
python
2 years ago
2.4 kB
2
Indexable
Never

import RPi.GPIO as GPIO
import time
 
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#set GPIO Pins
GPIO_TRIGGER1 = 18
GPIO_ECHO1 = 24
GPIO_TRIGGER2 = 17
GPIO_ECHO2 = 27
GPIO_TRIGGER3 = 22
GPIO_ECHO4 = 5
GPIO_TRIGGER4 = 6
GPIO_ECHO4 = 13
GPIO_TRIGGER5 = 19
GPIO_ECHO5 = 26
GPIO_TRIGGER6 = 25
GPIO_ECHO6 = 12




 
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER1, GPIO.OUT)
GPIO.setup(GPIO_ECHO1, GPIO.IN)
GPIO.setup(GPIO_TRIGGER2, GPIO.OUT)
GPIO.setup(GPIO_ECHO2, GPIO.IN)
GPIO.setup(GPIO_TRIGGER3, GPIO.OUT)
GPIO.setup(GPIO_ECHO3, GPIO.IN)
GPIO.setup(GPIO_TRIGGER4, GPIO.OUT)
GPIO.setup(GPIO_ECHO4, GPIO.IN)
GPIO.setup(GPIO_TRIGGER5, GPIO.OUT)
GPIO.setup(GPIO_ECHO5, GPIO.IN)
GPIO.setup(GPIO_TRIGGER6, GPIO.OUT)
GPIO.setup(GPIO_ECHO6, GPIO.IN)
 
def distance(GPIO_TRIGGER,GPIO_ECHO):
    # 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
 
if __name__ == '__main__':
    try:
        while True:
            
            dist1 = distance(GPIO_TRIGGER1,GPIO_ECHO1)
            print("Distance 1: "+str(dist1))
            dist2=distance(GPIO_TRIGGER2,GPIO_ECHO2)
            print("Distance 2: "+str(dist2))
            dist3=distance(GPIO_TRIGGER3,GPIO_ECHO3)
            print("Distance 3: "+str(dist3))
            dist4=distance(GPIO_TRIGGER4,GPIO_ECHO4)
            print("Distance 4: "+str(dist4))
            dist5=distance(GPIO_TRIGGER5,GPIO_ECHO5)
            print("Distance 5: "+str(dist5))
            dist6=distance(GPIO_TRIGGER6,GPIO_ECHO6)
            print("Distance 6: "+str(dist6))
            print (dist1,dist2,dist3,dist4,dist5,dist6)
            time.sleep(1)
 
        # Reset by pressing CTRL + C
    except KeyboardInterrupt:
        print("Measurement stopped by User")
        GPIO.cleanup()