Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Messung Entfernung
- import time
- import RPi.GPIO as GPIO
- import os
- import sys
- # define GPIO pins
- GPIOTrigger1 = 18
- GPIOEcho1 = 24
- GPIOTrigger2 = 25
- GPIOEcho2 = 23
- # function to measure the distance1
- def MeasureDistance1():
- # set trigger to high
- GPIO.output(GPIOTrigger1, True)
- # set trigger after 10µs to low
- time.sleep(0.00001)
- GPIO.output(GPIOTrigger1, False)
- # store initial start time
- StartTime1 = time.time()
- # store start time
- while GPIO.input(GPIOEcho1) == 0:
- StartTime1 = time.time()
- # store stop time
- while GPIO.input(GPIOEcho1) == 1:
- StopTime1 = time.time()
- # calculate distance
- TimeElapsed1 = StopTime1 - StartTime1
- Distance1 = TimeElapsed1 * 331.5 / 2
- return Distance1
- # function to measure the distance2
- def MeasureDistance2():
- # set trigger to high
- GPIO.output(GPIOTrigger2, True)
- # set trigger after 10µs to low
- time.sleep(0.00001)
- GPIO.output(GPIOTrigger2, False)
- # store initial start time
- StartTime2 = time.time()
- # store start time
- while GPIO.input(GPIOEcho2) == 0:
- StartTime2 = time.time()
- # store stop time
- while GPIO.input(GPIOEcho2) == 1:
- StopTime2 = time.time()
- # calculate distance
- TimeElapsed2 = StopTime2 - StartTime2
- Distance2 = TimeElapsed2 * 331.5 / 2
- return Distance2
- # main function
- def main():
- try:
- while True:
- Start = True
- while os.path.exists("/home/pi/RailRob/Messwerte/Start.txt"):
- Start = False
- while os.path.exists("/home/pi/RailRob/Messwerte/MessDaten.qwe"):
- file_out = open("/home/pi/RailRob/Messwerte/MessDaten.qwe","w") # w=ueberschreiben, a=anhaengen der Daten
- Zeitstempel = time.strftime("%Y_%m_%d_%H_%M_%S")
- #print("2")
- Distance1 = MeasureDistance1()
- print("1 = %.4f m" % Distance1)
- file_out.write(Zeitstempel+" Obenrechts %.4f\n" % Distance1)
- #print("3")
- Distance2 = MeasureDistance2()
- print("2 = %.4f m" % Distance2)
- file_out.write(Zeitstempel+" Obenlinks %.4f\n" % Distance2)
- #time.sleep(.1)
- #print("")
- file_out.close()
- os.rename("/home/pi/RailRob/Messwerte/MessDaten.qwe","/home/pi/RailRob/Messwerte/MessDaten.txt")
- time.sleep(.5)
- else:
- while Start == False and not os.path.exists("/home/pi/RailRob/Messwerte/Start.txt"):
- GPIO.cleanup()
- print("Messung beendet")
- sys.exit()
- Start=True
- except KeyboardInterrupt:
- print("Measurement stopped by user")
- GPIO.cleanup()
- if __name__ == '__main__':
- # use GPIO pin numbering convention
- GPIO.setmode(GPIO.BCM)
- # set up GPIO pins
- GPIO.setup(GPIOTrigger1, GPIO.OUT)
- GPIO.setup(GPIOEcho1, GPIO.IN)
- GPIO.setup(GPIOTrigger2, GPIO.OUT)
- GPIO.setup(GPIOEcho2, GPIO.IN)
- # set trigger to false
- GPIO.output(GPIOTrigger1, False)
- GPIO.output(GPIOTrigger2, False)
- # call main function
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement