-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdistance_detector.py
executable file
·72 lines (56 loc) · 1.82 KB
/
distance_detector.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python
from gpio_module import *
#
# Lets play with ultra sound
#
class DistanceDetector (GPIO_Module):
TRIG_PIN = 17
ECHO_PIN = 27
def __init__(self):
self.setup()
GPIO.setup(self.TRIG_PIN, GPIO.OUT)
GPIO.setup(self.ECHO_PIN, GPIO.IN)
GPIO.output(self.TRIG_PIN, GPIO.LOW)
def measure(self):
# Let the sensor to rest a bit:
time.sleep(0.1)
# Tigger sound pulse:
GPIO.output(self.TRIG_PIN, True)
# for 10 micro seconds
time.sleep(0.00001)
# stop sound pulse
GPIO.output(self.TRIG_PIN, False)
# Now, listen/receive the pulse
TIME_LIMIT_SEC = 1
start = time.time()
echo_start = -1
echo_stop = -1
while time.time() - start < TIME_LIMIT_SEC:
if GPIO.input(self.ECHO_PIN) != 0:
echo_start = time.time()
break
start = time.time()
while time.time() - start < TIME_LIMIT_SEC:
if GPIO.input(self.ECHO_PIN) == 0:
echo_stop = time.time()
break
if echo_stop < 0 or echo_start < 0:
return -1
# distance = speed of sound / 2 * time diff (in centimeters)
return (echo_stop - echo_start) * 17014
def distance_over_time(self, time_interval):
pos_count = 0
false_count = 0
collective = 0
current_measure_start=time.time()
while time.time() - current_measure_start < time_interval:
reading = self.measure()
if reading > 0:
pos_count += 1
collective += reading
else:
false_count += 1
if(pos_count > false_count * 2):
return collective/pos_count
else:
return -1