-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproximity_sensor.py
48 lines (39 loc) · 1.29 KB
/
proximity_sensor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import time
try:
from RPi import GPIO
GPIO.setmode(GPIO.BOARD)
except ImportError:
print("Error found importing RPi mo")
GPIO_TRIGGER = 10
GPIO_ECHO = 8
def measure_distance_from_sensor():
print("Requesting distance measure")
trigger_distance_measure_signal()
distance = read_distance_using_time_elapsed_between_echos()
print("Measured Distance = %.1f cm" % distance)
return distance
def trigger_distance_measure_signal():
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
def read_distance_using_time_elapsed_between_echos():
start_time = time.time()
stop_time = time.time()
print("Starting distance read")
start_read_time = time.time()
while GPIO.input(GPIO_ECHO) == 0:
start_time = time.time()
if time.time() - start_read_time > 1:
break
start_read_time = time.time()
while GPIO.input(GPIO_ECHO) == 1:
stop_time = time.time()
if time.time() - start_read_time > 1:
break
time_elapsed = stop_time - start_time
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (time_elapsed * 34300) / 2
return distance