-
Notifications
You must be signed in to change notification settings - Fork 53
/
sonar.py
131 lines (83 loc) · 2.6 KB
/
sonar.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import RPi.GPIO as GPIO
import os
import time
import atexit
import sys
from subprocess import call
import configure
def setup():
for i in range(3):
GPIO.setup(TRIG[i],GPIO.OUT)
GPIO.setup(ECHO[i],GPIO.IN)
GPIO.output(TRIG[i], False)
print "Waiting For Sensor To Settle"
#if ('LTRIG' in os.environ):
# TRIG = [int(os.environ['LTRIG']),
# int(os.environ['CTRIG']),
# int(os.environ['RTRIG'])]
# ECHO = [int(os.environ['LECHO']),
# int(os.environ['CECHO']),
# int(os.environ['RECHO'])]
if ('LTRIG' in configure.data):
TRIG = [int(configure.data['LTRIG']),
int(configure.data['CTRIG']),
int(configure.data['RTRIG'])]
ECHO = [int(configure.data['LECHO']),
int(configure.data['CECHO']),
int(configure.data['RECHO'])]
GPIO.setmode(GPIO.BCM)
setup()
def turnOffGPIO():
GPIO.cleanup()
atexit.register(turnOffGPIO)
def raw_distance(TRIG, ECHO):
#check a sonar with trigger argv1 and echo argv2
#example usage
#python sonar.py 22 27
# recommended for auto-disabling motors on shutdown!
GPIO.setmode(GPIO.BCM)
print "Distance Measurement In Progress"
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG, False)
print "Waiting For Sensor To Settle"
time.sleep(2)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
print "Distance:",distance,"cm"
def distance(i):
# print "Distance Measurement In Progress"
GPIO.output(TRIG[i], True)
time.sleep(0.00001)
GPIO.output(TRIG[i], False)
pulse_end = 0;
pulse_start = 0;
while GPIO.input(ECHO[i])==0:
pulse_start = time.time()
while GPIO.input(ECHO[i])==1:
pulse_end = time.time()
if (pulse_end == 0 or pulse_start==0):
return 1000
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
# print "Distance:",distance,"cm"
return distance
def ldist():
return distance(0)
def rdist():
return distance(2)
def cdist():
return distance(1)
if __name__ == "__main__":
TRIG = int(sys.argv[1])
ECHO = int(sys.argv[2])
raw_distance(TRIG, ECHO)