From 8fd84831216315ffbf83f4f3da84361046bbec82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ebbe=20Ba=C3=9F?= Date: Sat, 9 Jul 2022 23:55:42 +0200 Subject: [PATCH] next test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Ebbe Baß --- test.py | 54 ++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/test.py b/test.py index 846eb13..1defddc 100644 --- a/test.py +++ b/test.py @@ -1,15 +1,49 @@ -import smbus +import RPi.GPIO as GPIO import time -address = 0x57 -sensor = smbus.SMBus(1) +GPIO.setmode(GPIO.BCM) -while True: - sensor.write_byte(address, 0x01) - - time.sleep(0.2) +GPIO_TRIGGER = 18 +GPIO_ECHO = 24 - bytes = sensor.read_i2c_block_data(address, 0, 3) - distance = ((bytes[0] << 16) + (bytes[1] << 8) + bytes[2]) / 10000 +GPIO.setup(GPIO_TRIGGER, GPIO.OUT) +GPIO.setup(GPIO_ECHO, GPIO.IN) - print(distance) \ No newline at end of file +def distanz(): + # setze Trigger auf HIGH + GPIO.output(GPIO_TRIGGER, True) + + # setze Trigger nach 0.01ms aus LOW + time.sleep(0.00001) + GPIO.output(GPIO_TRIGGER, False) + + StartZeit = time.time() + StopZeit = time.time() + + # speichere Startzeit + while GPIO.input(GPIO_ECHO) == 0: + StartZeit = time.time() + + # speichere Ankunftszeit + while GPIO.input(GPIO_ECHO) == 1: + StopZeit = time.time() + + # Zeit Differenz zwischen Start und Ankunft + TimeElapsed = StopZeit - StartZeit + # mit der Schallgeschwindigkeit (34300 cm/s) multiplizieren + # und durch 2 teilen, da hin und zurueck + distanz = (TimeElapsed * 34300) / 2 + + return distanz + +if __name__ == '__main__': + try: + while True: + abstand = distanz() + print ("Gemessene Entfernung = %.1f cm" % abstand) + time.sleep(1) + + # Beim Abbruch durch STRG+C resetten + except KeyboardInterrupt: + print("Messung vom User gestoppt") + GPIO.cleanup() \ No newline at end of file