parent
1428fa5722
commit
8fd8483121
52
test.py
52
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)
|
||||
GPIO_TRIGGER = 18
|
||||
GPIO_ECHO = 24
|
||||
|
||||
time.sleep(0.2)
|
||||
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
|
||||
GPIO.setup(GPIO_ECHO, GPIO.IN)
|
||||
|
||||
bytes = sensor.read_i2c_block_data(address, 0, 3)
|
||||
distance = ((bytes[0] << 16) + (bytes[1] << 8) + bytes[2]) / 10000
|
||||
def distanz():
|
||||
# setze Trigger auf HIGH
|
||||
GPIO.output(GPIO_TRIGGER, True)
|
||||
|
||||
print(distance)
|
||||
# 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()
|
Loading…
Reference in New Issue