-
Notifications
You must be signed in to change notification settings - Fork 1
/
Ultrasonic.py
60 lines (47 loc) · 1.23 KB
/
Ultrasonic.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
import RPi.GPIO as GPIO
import time
from Car import Car
GPIO.setwarnings(False)
EchoPin = 18
TrigPin = 16
GPIO.setmode(GPIO.BOARD)
GPIO.setup(EchoPin, GPIO.IN)
GPIO.setup(TrigPin, GPIO.OUT)
def distance():
GPIO.output(TrigPin, GPIO.LOW)
time.sleep(0.000002)
GPIO.output(TrigPin, GPIO.HIGH)
time.sleep(0.000015)
GPIO.output(TrigPin, GPIO.LOW)
t3 = time.time()
while not GPIO.input(EchoPin):
t4 = time.time()
if (t4 - t3) > 0.03:
return -1
t1 = time.time()
while GPIO.input(EchoPin):
t5 = time.time()
if (t5 - t1) > 0.03:
return -1
t2 = time.time()
time.sleep(0.01)
return ((t2 - t1) * 340 / 2) * 100
if __name__ == '__main__':
car = Car()
print(f"Starting: {distance()}")
left = 75
right = 75
try:
while True:
if abs(distance() - 50) > 2:
while abs(distance() - 50) > 2:
if distance() < 50:
car.control_car(-left, -right)
else:
car.control_car(left, right)
else:
car.control_car(0, 0)
except:
car.stop()
print(f"Ending: {distance()}")
car.stop()