-
Notifications
You must be signed in to change notification settings - Fork 0
/
straight.py
122 lines (104 loc) · 2.89 KB
/
straight.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
import gopigo
import sys
import time
LEFT = 0
RIGHT = 1
SPEED = int(sys.argv[1])
INC = (SPEED / 100) * 10 #7#15
SAFE_DISTANCE = 45
USS = 15
TRIM = int(sys.argv[2])
CORRECTION = sys.argv[3] == "true"
print(CORRECTION)
# Might as well try this out, probably doesn't do anything though
gopigo.disable_encoders()
gopigo.enable_encoders()
gopigo.trim_write(TRIM)
ADDRESS = 0x08
ENC_READ_CMD = [53]
import smbus
bus = smbus.SMBus(1)
def write_i2c_block(address, block):
try:
op = bus.write_i2c_block_data(address, 1, block)
time.sleep(0.005)
return op
except IOError:
return -1
return 1
def enc_read(motor):
write_i2c_block(ADDRESS, ENC_READ_CMD+[motor,0,0])
#time.sleep(0.01)
#time.sleep(0.08)
try:
b1 = bus.read_byte(ADDRESS)
b2 = bus.read_byte(ADDRESS)
except IOError:
return -1
if b1 != -1 and b2 != -1:
v = b1 * 256 + b2
return v
else:
return -1
US_CMD = [117]
def us_dist(pin):
write_i2c_block(ADDRESS, US_CMD+[pin,0,0])
time.sleep(0.01)
#time.sleep(0.08)
try:
b1 = bus.read_byte(ADDRESS)
b2 = bus.read_byte(ADDRESS)
except IOError:
return -1
if b1 != -1 and b2 != -1:
v = b1 * 256 + b2
return v
else:
return -1
time.sleep(0.1)
initial_ticks_left = enc_read(LEFT)
time.sleep(0.1)
initial_ticks_right = enc_read(RIGHT)
elapsed_ticks_left = 0
elapsed_ticks_right = 0
try:
try:
gopigo.set_speed(SPEED)
gopigo.fwd()
while True:
#time.sleep(0.12)
t = time.time()
dist = us_dist(USS)
print("Dist: " + str(dist))
if dist < SAFE_DISTANCE:
gopigo.stop()
while dist < SAFE_DISTANCE:
dist = us_dist(USS)
time.sleep(0.01)
gopigo.fwd()
#time.sleep(0.1)
elapsed_ticks_left = enc_read(LEFT) - initial_ticks_left
#time.sleep(0.1)
elapsed_ticks_right = enc_read(RIGHT) - initial_ticks_right
print("L: " + str(elapsed_ticks_left) + "\tR: " + str(elapsed_ticks_right))
if elapsed_ticks_left > elapsed_ticks_right:
print("RIGHT SLOW")
if CORRECTION:
gopigo.set_left_speed(SPEED - INC)
gopigo.set_right_speed(SPEED + INC)
elif elapsed_ticks_left < elapsed_ticks_right:
print("LEFT SLOW")
if CORRECTION:
gopigo.set_left_speed(SPEED + INC)
gopigo.set_right_speed(SPEED - INC)
else:
print("Equal")
if CORRECTION:
gopigo.set_left_speed(SPEED)
gopigo.set_right_speed(SPEED)
print(time.time() - t)
except Exception, e:
print(e)
except KeyboardInterrupt:
pass
gopigo.stop()