-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpiwars_bot.py
102 lines (84 loc) · 2.67 KB
/
piwars_bot.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
from contextlib import contextmanager
import piconzero as pz
from hcsr04 import getDistance as pz_get_distance
import RPi.GPIO as GPIO
import time
class DistanceSensor:
def __init__(self, echo, trigger):
self.echo = echo
self.trigger = trigger
GPIO.setup(self.trigger, GPIO.OUT)
GPIO.setup(self.echo, GPIO.IN)
def get_distance(self):
# Send 10us pulse to trigger
GPIO.output(self.trigger, True)
time.sleep(0.00001)
GPIO.output(self.trigger, False)
start = time.time()
count = time.time()
while GPIO.input(self.echo)==0 and time.time()-count<0.1:
start = time.time()
count=time.time()
stop=count
while GPIO.input(self.echo)==1 and time.time()-count<0.1:
stop = time.time()
# Calculate pulse length
elapsed = stop-start
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distance = elapsed * 34000
# That was the distance there and back so halve the value
distance = distance / 2
return distance
class _robot(object):
def __init__(self):
pz.init()
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
# 24, 25 is BCM 18, 22
self.sensor_right = DistanceSensor(echo=18, trigger=22)
# 22, 23 is BCM 15, 16
self.sensor_left = DistanceSensor(echo=15, trigger=16)
def cleanup(self):
GPIO.cleanup()
@property
def forward_distance(self):
return pz_get_distance()
@property
def left_distance(self):
return self.sensor_left.get_distance()
@property
def right_distance(self):
return self.sensor_right.get_distance()
def set_motors(self, left_speed, right_speed):
pz.setMotor(0, max(min(int(left_speed), 100), -100))
pz.setMotor(1, max(min(int(right_speed), 100), -100))
def set_left(self, left_speed):
pz.setMotor(0, max(min(int(left_speed), 100), -100))
def set_right(self, right_speed):
pz.setMotor(1, max(min(int(right_speed), 100), -100))
def forward(self, speed):
"""Both motors forward"""
pz.forward(speed)
def left(self, speed):
pz.spinLeft(speed)
def right(self, speed):
pz.spinRight(speed)
def backward(self, speed):
pz.forward(-speed)
def stop(self):
"""Both motors stop"""
pz.stop()
@contextmanager
def Robot():
"""Use this to ensure robot stops if inner code
crashes"""
r = None
try:
r = _robot()
yield r
finally:
pz.stop()
pz.cleanup()
if r:
r.cleanup()