-
Notifications
You must be signed in to change notification settings - Fork 0
/
ultrasonic_sensors.py
104 lines (74 loc) · 2.62 KB
/
ultrasonic_sensors.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
import RPi.GPIO as GPIO
import time
class front_sensor():
def __init__(self):
GPIO.setmode(GPIO.BCM)
self.TRIG = 20
self.ECHO = 21
GPIO.setup(self.TRIG, GPIO.OUT)
GPIO.setup(self.ECHO, GPIO.IN)
self.distance = 99999
self.cycle_on = False
self.i = 1
print " front sensor initialized "
def read_distance(self):
GPIO.setmode(GPIO.BCM)
GPIO.output(self.TRIG, True)
time.sleep(0.00001)
GPIO.output(self.TRIG, False)
while GPIO.input(self.ECHO) == 0:
self.pulse_start = time.time()
while GPIO.input(self.ECHO) == 1:
self.pulse_end = time.time()
self.pulse_duration = self.pulse_end - self.pulse_start
self.tmp_distance = self.pulse_duration * 17150
if self.distance == 0 :
self.distance = round(self.tmp_distance, 2)
elif ( self.tmp_distance < 3000):
self.distance = round(self.tmp_distance, 2)
#else:
# self.distance = 99999
def read_distance_cycle(self):
self.cycle_on = True
while self.cycle_on == True:
self.read_distance()
time.sleep(.1)
print " !!!!!!!!!!!!!!front distance : stop reading in cycle"
def stop_reading(self):
self.cycle_on = False
print "******** stop reading"
class rear_sensor():
def __init__(self):
GPIO.setmode(GPIO.BCM)
self.TRIG = 12
self.ECHO = 16
GPIO.setup(self.TRIG, GPIO.OUT)
GPIO.setup(self.ECHO, GPIO.IN)
self.distance = 99999
self.cycle_on = False
self.i = 1
print " rear sensor initialized "
def read_distance(self):
GPIO.setmode(GPIO.BCM)
GPIO.output(self.TRIG, True)
time.sleep(0.00001)
GPIO.output(self.TRIG, False)
while GPIO.input(self.ECHO) == 0:
self.pulse_start = time.time()
while GPIO.input(self.ECHO) == 1:
self.pulse_end = time.time()
self.pulse_duration = self.pulse_end - self.pulse_start
self.tmp_distance = self.pulse_duration * 17150
if self.distance == 0 :
self.distance = round(self.tmp_distance, 2)
elif ( self.tmp_distance < 3000):
self.distance = round(self.tmp_distance, 2)
def read_distance_cycle(self):
self.cycle_on = True
while self.cycle_on == True:
self.read_distance()
time.sleep(.1)
print " !!!!!!!!!!!!!!rear distance : stop reading in cycle"
def stop_reading(self):
self.cycle_on = False
print "******** stop reading"