/
raftBerry.py
479 lines (460 loc) · 14.5 KB
/
raftBerry.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#raftBerry
#A python implementation of an autonomous, GPS controlled, electric floating dock.
#Use this code at your own risk, if you intend to build this device, please be careful, I am not responsible for
#anything that happens if you use this code. The code doesn't do any kind of collision avoidance with land or
#other crafts. Use at your own risk. This code is pieced together from many sources. Please feel free to submit
#corrections and improvements.
#see https://github.com/whyvas/raftBerry for updates, wiring diagrams and pictures.
from math import radians, sin, cos, sqrt, asin
from gps import *
from pykml import parser
import os
import smbus
import time
import threading
import math
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
bus = smbus.SMBus(1)
address = 0x1e
leftspeed = 0
rightspeed = 0
#GPIO pin definitions
AUTOMAN = 27
PORTDIR = 24
PORTLOW = 13
PORTMED = 25
PORTHIGH = 8
STARDIR = 7
STARLOW = 11
STARMED = 9
STARHIGH = 10
JOYUP = 17
JOYDOWN = 6
JOYLEFT = 5
JOYRIGHT = 4
SHUTDOWN = 22
#Setup GPIO input pins
GPIO.setup(JOYLEFT, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(JOYDOWN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(JOYRIGHT, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(JOYUP, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(AUTOMAN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(SHUTDOWN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#Setup GPIO output pins
GPIO.setup(STARHIGH, GPIO.OUT, pull_up_down=GPIO.PUD_UP)
GPIO.setup(STARMED, GPIO.OUT, pull_up_down=GPIO.PUD_UP)
GPIO.setup(STARLOW, GPIO.OUT, pull_up_down=GPIO.PUD_UP)
GPIO.setup(STARDIR, GPIO.OUT, pull_up_down=GPIO.PUD_UP)
GPIO.setup(PORTHIGH, GPIO.OUT, pull_up_down=GPIO.PUD_UP)
GPIO.setup(PORTMED, GPIO.OUT, pull_up_down=GPIO.PUD_UP)
GPIO.setup(PORTLOW, GPIO.OUT, pull_up_down=GPIO.PUD_UP)
GPIO.setup(PORTDIR, GPIO.OUT, pull_up_down=GPIO.PUD_UP)
#Function to turn off all motors
def motorsOff(channel):
GPIO.output(STARHIGH, 1)
GPIO.output(STARMED, 1)
GPIO.output(STARLOW, 1)
GPIO.output(STARDIR, 1)
GPIO.output(PORTHIGH, 1)
GPIO.output(PORTMED, 1)
GPIO.output(PORTLOW, 1)
GPIO.output(PORTDIR, 1)
print "Motors off"
#Turn off motors, cleanup GPIO and shutdown the pi
def emergencyStop(channel):
global leftspeed,rightspeed
print "Emergency stop button pressed"
leftspeed=0
rightspeed=0
motorsOff(0)
GPIO.cleanup()
os.system('shutdown now -h')
exit()
#Read joystick inputs
def joyUp(channel):
global leftspeed,rightspeed
print "Joystick up"
if leftspeed < 3:
leftspeed+=1
if rightspeed < 3:
rightspeed+=1
print'Left:',leftspeed, 'Right:',rightspeed
setSpeed()
def joyDown(channel):
global leftspeed, rightspeed
print "Joystick down"
if leftspeed > -3:
leftspeed-=1
if rightspeed > -3:
rightspeed-=1
print "Left:",leftspeed," Right:",rightspeed
setSpeed()
def joyLeft(channel):
print "Joystick left"
incRight()
print "Left:",leftspeed," Right:",rightspeed
setSpeed()
def joyRight(channel):
print "Joystick right"
incLeft()
print "Left:",leftspeed," Right:",rightspeed
setSpeed()
#increase left by 1, if left = 7 and right doesn't = 0, decrease right by 1
def decLeft():
global leftspeed
if leftspeed > -3:
leftspeed-=1
def incLeft():
global leftspeed, rightspeed
if leftspeed < 3:
leftspeed+=1
elif rightspeed > -3:
rightspeed-=1
def incRight():
global rightspeed, leftspeed
if rightspeed < 3:
rightspeed+=1
elif leftspeed > -3:
leftspeed-=1
def decRight():
global rightspeed
if rightspeed > -3:
rightspeed-=1
#Set relays for direction and speed.
def setSpeed():
global rightspeed, leftspeed
if rightspeed==3:
GPIO.output(STARHIGH,0)
GPIO.output(STARMED,0)
GPIO.output(STARLOW,0)
GPIO.output(STARDIR,0)
print "Set Right:",rightspeed
elif rightspeed==2:
GPIO.output(STARHIGH,1)
GPIO.output(STARMED,0)
GPIO.output(STARLOW,0)
GPIO.output(STARDIR,0)
print "Set Right:",rightspeed
elif rightspeed==1:
GPIO.output(STARHIGH,1)
GPIO.output(STARMED,1)
GPIO.output(STARLOW,0)
GPIO.output(STARDIR,0)
print "Set Right:",rightspeed
elif rightspeed==0:
GPIO.output(STARHIGH,1)
GPIO.output(STARMED,1)
GPIO.output(STARLOW,1)
GPIO.output(STARDIR,1)
print "Set Right:",rightspeed
elif rightspeed==-1:
GPIO.output(STARHIGH,1)
GPIO.output(STARMED,1)
GPIO.output(STARLOW,0)
GPIO.output(STARDIR,1)
print "Set Right:",rightspeed
elif rightspeed==-2:
GPIO.output(STARHIGH,1)
GPIO.output(STARMED,0)
GPIO.output(STARLOW,0)
GPIO.output(STARDIR,1)
print "Set Right:",rightspeed
elif rightspeed==-3:
GPIO.output(STARHIGH,0)
GPIO.output(STARMED,0)
GPIO.output(STARLOW,0)
GPIO.output(STARDIR,1)
print "Set Right:",rightspeed
if leftspeed==3:
GPIO.output(PORTHIGH,0)
GPIO.output(PORTMED,0)
GPIO.output(PORTLOW,0)
GPIO.output(PORTDIR,0)
print "Set Left:",leftspeed
elif leftspeed==2:
GPIO.output(PORTHIGH,1)
GPIO.output(PORTMED,0)
GPIO.output(PORTLOW,0)
GPIO.output(PORTDIR,0)
print "Set Left:",leftspeed
elif leftspeed==1:
GPIO.output(PORTHIGH,1)
GPIO.output(PORTMED,1)
GPIO.output(PORTLOW,0)
GPIO.output(PORTDIR,0)
print "Set Left:",leftspeed
elif leftspeed==0:
GPIO.output(PORTHIGH,1)
GPIO.output(PORTMED,1)
GPIO.output(PORTLOW,1)
GPIO.output(PORTDIR,1)
print "Set Left:",leftspeed
elif leftspeed==-1:
GPIO.output(PORTHIGH,1)
GPIO.output(PORTMED,1)
GPIO.output(PORTLOW,0)
GPIO.output(PORTDIR,1)
print "Set Left:",leftspeed
elif leftspeed==-2:
GPIO.output(PORTHIGH,1)
GPIO.output(PORTMED,0)
GPIO.output(PORTLOW,0)
GPIO.output(PORTDIR,1)
print "Set Left:",leftspeed
elif leftspeed==-3:
GPIO.output(PORTHIGH,0)
GPIO.output(PORTMED,0)
GPIO.output(PORTLOW,0)
GPIO.output(PORTDIR,1)
print "Set Left:",leftspeed
#Function that returns the angle remaining to get to desired bearing. Negative for left, positive for right.
def turnOffset(chead,dhead):
if (chead > dhead):
if ((chead-dhead) >= 180):
return(360-chead+dhead)
else:
return((chead-dhead)*-1)
if (chead < dhead):
if ((dhead-chead) >= 180):
return((360-dhead+chead)*-1)
else:
return(dhead-chead)
#Functions to read the bearing from the digital compass.
def read_byte(adr):
return bus.read_byte_data(address, adr)
def read_word(adr):
high = bus.read_byte_data(address, adr)
low = bus.read_byte_data(address, adr+1)
val = (high << 8) + low
return val
def read_word_2c(adr):
val = read_word(adr)
if (val >= 0x8000):
return -((65535 - val) + 1)
else:
return val
def write_byte(adr, value):
bus.write_byte_data(address, adr, value)
def getBearing():
write_byte(0, 0b01110000) # Set to 8 samples @ 15Hz
write_byte(1, 0b00100000) # 1.3 gain LSb / Gauss 1090 (default)
write_byte(2, 0b00000000) # Continuous sampling
scale = 0.92
x_out = read_word_2c(3) * scale
y_out = read_word_2c(7) * scale
z_out = read_word_2c(5) * scale
bearing = math.atan2(y_out, x_out)
if (bearing < 0):
bearing += 2 * math.pi
return(math.degrees(bearing))
#GPS Functions to get location, time, speed, etc
class GpsController(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
self.running = False
def run(self):
self.running = True
while self.running:
# grab EACH set of gpsd info to clear the buffer
self.gpsd.next()
def stopController(self):
self.running = False
@property
def fix(self):
return self.gpsd.fix
@property
def utc(self):
return self.gpsd.utc
@property
def satellites(self):
return self.gpsd.satellites
#Haversine function to return distance between two coordinates
def haversine(lat1, lon1, lat2, lon2):
R = 6372.8 # Earth radius in kilometers
dLat = radians(lat2 - lat1)
dLon = radians(lon2 - lon1)
lat1 = radians(lat1)
lat2 = radians(lat2)
a = sin(dLat/2)**2 + cos(lat1)*cos(lat2)*sin(dLon/2)**2
c = 2*asin(sqrt(a))
return R * c * 1000
#Function to calculate the bearing between two waypoints.
def bearing(lat1, lon1, lat2, lon2):
rlat1 = math.radians(lat1)
rlat2 = math.radians(lat2)
rlon1 = math.radians(lon1)
rlon2 = math.radians(lon2)
dlon = math.radians(lon2-lon1)
b = math.atan2(math.sin(dlon)*math.cos(rlat2),math.cos(rlat1)*math.sin(rlat2)-math.sin(rlat1)*math.cos(rlat2)*math.cos(dlon)) # bearing calc
bd = math.degrees(b)
br,bn = divmod(bd+360,360) # the bearing remainder and final bearing
return bn
#Function to return the closest waypoint to current position
def findClosest():
closestd = 10000000
closesti = 0
clon = gpsc.fix.latitude
clat = gpsc.fix.longitude
for x in range(0,len(root.Document.Folder.Placemark)):
lat = float(str(root.Document.Folder.Placemark[x].Point.coordinates).split(",")[0])
lon = float(str(root.Document.Folder.Placemark[x].Point.coordinates).split(",")[1])
dist = haversine(lat,lon,clat,clon)
# print str(lat)+ " " +str(lon)+" "+str(dist)
if (closestd > dist):
closesti = x
closestd = dist
#print "Closest index is: " + str(closesti)
#print "Closest distance is: " + str(closestd)
return closesti
#Set the speed and direction based on turn offset
def autoSpeed(turn):
global leftspeed,rightspeed
if (turn > 150):
leftspeed=3
rightspeed=-3
if (turn > 120 and turn <= 150):
leftspeed=3
rightspeed=-2
if (turn > 90 and turn <= 120):
leftspeed=3
rightspeed=-1
if (turn > 60 and turn <= 90):
leftspeed=3
rightspeed=0
if (turn > 30 and turn <= 60):
leftspeed=3
rightspeed=1
if (turn > 10 and turn <= 30):
leftspeed=3
rightspeed=2
if (turn > -10 and turn <= 10):
leftspeed=3
rightspeed=3
if (turn > -30 and turn <= -10):
leftspeed=2
rightspeed=3
if (turn > -60 and turn <= -30):
leftspeed=1
rightspeed=3
if (turn > -90 and turn <= -60):
leftspeed=0
rightspeed=3
if (turn > -120 and turn <= -90):
leftspeed=-1
rightspeed=3
if (turn > -150 and turn <= -120):
leftspeed=-2
rightspeed=3
if (turn < -150 ):
leftspeed=-3
rightspeed=3
if (waypoint < (len(root.Document.Folder.Placemark)-1)):
setSpeed()
else:
leftspeed=0
rightspeed=0
setSpeed()
#Read and parse KML file for GPS tour.
print "Loading waypoints from file"
root = parser.fromstring(open('/home/pi/piDock/LacLong.kml', 'r').read())
#Launch GPSD
print("Launching gpsd...")
os.system("sudo gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock")
time.sleep(2)
#Main program loop
if __name__ == '__main__':
gpsc = GpsController()
waypoint = 0
#Add kml file loading into linked list here
try:
gpsc.start()
while True:
#Replace true below with manual/auto switch check
if GPIO.input(AUTOMAN):
print "Entering autonomous mode, waiting for GPS lock to find closest waypoint in list"
while(gpsc.fix.mode!=3):
time.sleep(1)
waypoint = findClosest()
os.system('clear')
while GPIO.input(AUTOMAN):
dlat = float(str(root.Document.Folder.Placemark[waypoint].Point.coordinates).split(",")[1])
dlon = float(str(root.Document.Folder.Placemark[waypoint].Point.coordinates).split(",")[0])
currentBearing = getBearing()
clat = gpsc.fix.latitude
clon = gpsc.fix.longitude
distance = int(haversine(clat,clon,dlat,dlon))
print "============================================================"
print "raftBerry Autonomous mode"
print "============================================================"
print "Current Lat: " +str(clat)
print "Current Lon: " +str(clon)
print "Waypoint Lat: " +str(dlat)
print "Waypoint Lon: " +str(dlon)
print "Waypoint Index: " + str(waypoint)
print "Waypoint Distance: " + str(distance)+ "m"
print "Current Bearing: " + str(currentBearing)
print "Waypoint Bearing: " + str(bearing(clat, clon,dlat, dlon))
print "Turn Offset: " + str(turnOffset(currentBearing,bearing(clat,clon,dlat,dlon)))
print "UTC Time: ", gpsc.utc[11:-5]
print "GPS Error: "+ str(gpsc.fix.epx) + "m"
if gpsc.fix.mode == 0:
print "GPS Status: No mode"
elif gpsc.fix.mode == 1:
print "GPS Status: No Fix"
elif gpsc.fix.mode == 2:
print "GPS Status: 2D Lock"
elif gpsc.fix.mode == 3:
print "GPS Status: 3D Lock"
print "Closest waypoint: " +str(findClosest())
print "Port motor speed: "+ str(leftspeed)
print "Starboard motor speed: "+str(rightspeed)
print GPIO.input(AUTOMAN)
autoSpeed(turnOffset(currentBearing,bearing(clat,clon,dlat,dlon)))
if (distance < 10):
if (waypoint < (len(root.Document.Folder.Placemark)-1)):
waypoint+=1
else:
print "At the end of the loop"
print "Please switch to manual control"
motorsOff(0)
print "============================================================"
time.sleep(1)
os.system('clear')
if(GPIO.input(SHUTDOWN) ==0):
emergencyStop(0)
#change to check automan switch
if !GPIO.input(AUTOMAN):
motorsOff(0)
print "============================================================"
print "raftBerry manual mode"
print "============================================================"
leftspeed = 0
rightspeed = 0
setSpeed()
while !GPIO.input(AUTOMAN):
if(GPIO.input(SHUTDOWN) ==0):
emergencyStop(0)
if(GPIO.input(JOYUP) ==0):
joyUp(0)
if(GPIO.input(JOYDOWN) ==0):
joyDown(0)
if(GPIO.input(JOYLEFT) ==0):
joyLeft(0)
if(GPIO.input(JOYRIGHT) ==0):
joyRight(0)
time.sleep(.5)
#Ctrl C
except KeyboardInterrupt:
print "\nKeyboard interrupt caught, cleaning GPIO and exiting."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
finally:
print "Cleaning up GPIO"
GPIO.cleanup()
print "Stopping gps controller"
gpsc.stopController()
gpsc.join()
print "Done"