Repository navigation
Expand file tree
/
Copy pathmenuJoy.py
More file actions
492 lines (362 loc) · 16.4 KB
/
Copy pathmenuJoy.py
File metadata and controls
492 lines (362 loc) · 16.4 KB
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
480
481
482
483
484
485
486
487
488
489
490
491
492
# Code for Brian Corteil's Tiny 4WD robot, based on code from Brian as modified by Emma Norling.
# Subsequently modified by Tom Oinn to add dummy functions when no explorer hat is available,
# modified by Brian Corteil to use the redboard+ motor controller hat and a menu using the SDD1306 OLED display
# use any available joystick, use the new function in 1.0.6 of approxeng.input to get multiple
# axis values in a single call, use implicit de-structuring of tuples to reduce verbosity, add
# an exception to break out of the control loop on pressing SELECT etc.
from time import sleep, time
from board import SCL, SDA
import busio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306
# for ip address
import subprocess
# Create the I2C interface.
i2c = busio.I2C(SCL, SDA)
# is OLED fitted
OLEDflag = False
# Create the SSD1306 OLED class and setup the display
# The first two parameters are the pixel width and pixel height. Change these
# to the right size for your display!
try:
disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)
OLEDflag = True
except ValueError:
print('')
print('SSD1306 OLED Screen not found')
print('')
# hardware setup
# RoF
try:
# Try to import the sensors module
import sensors
# initalise ToF sensors
sensors.initialise()
except ModuleNotFoundError:
print("sensor library not available")
try:
# Attempt to import the REDBOARD HAT library. If this fails, because we're running somewhere
# that doesn't have the library, we create dummy functions for set_speeds and stop_motors which
# just print out what they'd have done. This is a fairly common way to deal with hardware that
# may or may not exist! Obviously if you're actually running this on one of Brian's robots you
# should have the Explorer HAT libraries installed, this is really just so I can test on my big
# linux desktop machine when coding.
import redboard
print('Redboard HAT library available.')
def set_speeds(power_left, power_right):
"""
As we have an motor hat, we can use the motors
:param power_left:
Power to send to left motor
:param power_right:
Power to send to right motor, will be inverted to reflect chassis layout
"""
redboard.M1(-power_right)
redboard.M2(power_left)
def stop_motors():
"""
As we have an motor hat, stop the motors using their motors call
"""
redboard.M1(0)
redboard.M2(0)
except ImportError:
print('No Redboard HAT library available, using dummy functions.')
def set_speeds(power_left, power_right):
"""
No motor hat - print what we would have sent to it if we'd had one.
"""
print('Left: {}, Right: {}'.format(power_left, power_right))
sleep(0.1)
def stop_motors():
"""
No motor hat, so just print a message.
"""
print('Motors stopping')
# All we need, as we don't care which controller we bind to, is the ControllerResource
from approxeng.input.selectbinder import ControllerResource
class RobotStopException(Exception):
"""
The simplest possible subclass of Exception, we'll raise this if we want to stop the robot
for any reason. Creating a custom exception like this makes the code more readable later.
"""
pass
def mixer(yaw, throttle, max_power=100):
"""
Mix a pair of joystick axes, returning a pair of wheel speeds. This is where the mapping from
joystick positions to wheel powers is defined, so any changes to how the robot drives should
be made here, everything else is really just plumbing.
:param yaw:
Yaw axis value, ranges from -1.0 to 1.0
:param throttle:
Throttle axis value, ranges from -1.0 to 1.0
:param max_power:
Maximum speed that should be returned from the mixer, defaults to 100
:return:
A pair of power_left, power_right integer values to send to the motor driver
"""
left = throttle + yaw
right = throttle - yaw
scale = float(max_power) / max(1, abs(left), abs(right))
return int(left * scale), int(right * scale)
# functions for OLED display and setup display
if OLEDflag:
# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('/home/pi/RedBoard/system/Greenscr.ttf', 12)
def clearDisplay():
draw.rectangle((0, 0, width, height), outline=0, fill=0)
def lineOneText(text):
draw.rectangle((0, 0, width, height / 2), outline=0, fill=0)
draw.text((0, 2), text, font=font, fill=255)
def lineTwoText(text):
draw.rectangle((0, 32, width, height / 2), outline=0, fill=0)
draw.text((0, 16), text, font=font, fill=255)
def updateDisplay():
disp.image(image)
disp.show()
else:
def clearDisplay():
pass
def lineOneText(text):
print(text)
def lineTwoText(text):
print(text)
def updateDisplay():
pass
# end OLED functions
def homeDisplayUpdate():
mainBattery = str(batteryVoltage())
if len(mainBattery) == 4:
mainBattery += "0"
text1 = "Batt: " + mainBattery + "V"
lineOneText(text1)
if not joystick.battery_level == None:
joy_battery_level = joystick.battery_level * 100
text2 = "Joy: " + str(joy_battery_level) + "%"
else:
text2 = "Joy: Not supported"
lineTwoText(text2)
print(text1 + " " + text2)
def batteryVoltage():
ADC_bat_conversion_Value = 1098.0
voltage = readADC()
conversion_0 = (voltage[1]) + (voltage[0] << 8)
volts_in = conversion_0 / ADC_bat_conversion_Value
volts_in = round(volts_in, 2)
return volts_in
def readADC(channel=0, i2cBus=1, address=0x48): # default are for the ADC on the redboard
bus = smbus.SMBus(i2cBus)
bus.write_i2c_block_data(address, 0x01, [0xc3, 0x83])
adc = bus.read_i2c_block_data(address, 0x00, 2)
return adc
# setup for main loop
menu = {'Manual': True, 'Line': False, 'Maze': False, 'Toxic': False, 'Zombie': False, 'IP': False, 'Exit': False,
'Shutdown': False, 'Reboot': False}
menuItems = list(menu)
menuLenght = len(menuItems)
menuIndex = 0
lastMenuIndex = menuIndex
menuFlag = False
mode = menuIndex
oldMode = mode
currentMenu = {**menu}
displayTimeOut = 1 # time in seconds for display to blank or return to home screen
displayTimeOutFlag = False
savedTime = time()
currentTime = time()
newModeFlag = False
lastBatteryTime = time()
refreshTime = 60 # in seconds
lastRefresh = time() - refreshTime
displayHomeScreenFlag = False
# maze flags and verables
tofRunningFlag = False
tofSensorsOn = False
# End of setup
# Outer try / except catches the RobotStopException we just defined, which we'll raise when we want to
# bail out of the loop cleanly, shutting the motors down. We can raise this in response to a button press
try:
while True:
# Inner try / except is used to wait for a controller to become available, at which point we
# bind to it and enter a loop where we read axis values and send commands to the motors.
try:
# Bind to any available joystick, this will use whatever's connected as long as the library
# supports it.
with ControllerResource(dead_zone=0.1, hot_zone=0.2) as joystick:
print('Controller found, press SELECT button to exit, use left stick for power, right to steer.')
print(joystick.controls)
# Loop until the joystick disconnects, or we deliberately stop by raising a
# RobotStopException
while joystick.connected:
# Get joystick values from the left & right analogue sticks
x_axis, y_axis = joystick['rx', 'ly']
# Get power from mixer function
if menu['Manual']:
power_left, power_right = mixer(yaw=x_axis, throttle=y_axis)
set_speeds(power_left, power_right)
#print("Manaual Mode on")
else:
stop_motors()
# Get a ButtonPresses object containing everything that was pressed since the last
# time around this loop.
joystick.check_presses()
# Print out any buttons that were pressed, if we had any
if joystick.has_presses:
print(joystick.presses)
# If SELECT was pressed, raise a RobotStopException to bail out of the loop
if 'select' in joystick.presses:
raise RobotStopException()
if 'start' in joystick.presses:
if menu['Manual']:
menu['Manual'] = False
else:
menu['Manual'] = True
# menu flag set/unset ** is the unpacking operator and enables a shallow copy of the dictionary
if 'home' in joystick.presses:
clearDisplay()
if menuFlag:
menuFlag = False
menu = {**currentMenu}
print("Menu exitied")
displayHomeScreenFlag = True
#print(menu)
else:
currentMenu = {**menu}
# print(currentMenu)
menuFlag = True
if menu[menuItems[mode]]:
text = "MODE: " + menuItems[mode]
print(text)
else:
text = "No mode selected"
print("menu entered")
lineOneText(text)
updateDisplay()
for key in menuItems:
menu[key] = False
#print("MenuFlag status: " + str(menuFlag))
# if d up is pressed move menu up
if 'dup' in joystick.presses and menuFlag:
menuIndex -= 1
if menuIndex < 0:
menuIndex = menuLenght -1
# if d down is pressed move menu down
if 'ddown' in joystick.presses and menuFlag:
menuIndex += 1
if menuIndex == menuLenght:
menuIndex = 0
# if 'cycle' is press when in menu select assign current menu item to mode
if 'circle' in joystick.presses and menuFlag:
oldMode = mode
mode = menuIndex
menuFlag = False
newModeFlag = True
for key in menuItems:
if key == menuItems[mode]:
menu[key] = True
else:
menu[key] = False
savedTime = time()
displayTimeOutFlag = True
displayTimeOut = 2
# print menu item to command line
if lastMenuIndex != menuIndex and menuFlag:
text = menuItems[menuIndex]
print(text)
lineOneText(text)
print("Press 'O' to select")
lineTwoText("'O' to select")
lastMenuIndex = menuIndex
updateDisplay()
# screen blanking or home screen update
# home screen refresh time in seconds
currentTime = time()
if displayTimeOutFlag and (currentTime - savedTime > displayTimeOut):
clearDisplay()
displayTimeOutFlag = False
displayHomeScreenFlag = True
updateDisplay()
if menuFlag == False and displayTimeOutFlag == False:
if currentTime - lastRefresh > refreshTime or displayHomeScreenFlag:
homeDisplayUpdate()
lastRefresh = time()
displayHomeScreenFlag = False
updateDisplay()
# end of screen blanking or home screen update
if menu['Manual']:
# code to be run while in manual mode here
pass
if menu['Line']:
# code for line following here
pass
if menu['Maze']:
pass
if menu['Toxic']:
# code for Toxic here
pass
if menu['Zombie']:
# code for Zombie here
pass
if menu['IP']:
# code for displaying IP address
cmd = "hostname -I | cut -d\' \' -f1"
IP = subprocess.check_output(cmd, shell=True).decode("utf-8")
print(IP)
lineOneText('')
lineTwoText(IP)
updateDisplay()
menu['IP'] = False
newModeFlag = False
mode = 0
savedTime = time()
displayTimeOutFlag = True
displayTimeOut = 5
if menu['Exit']:
# Exit to commard line
newModeFlag = False
raise RobotStopException()
if menu['Shutdown']:
# Shutdown the Raspberry Pi
newModeFlag = False
cmd = "sudo halt"
subprocess.call(cmd, shell=True)
if menu['Reboot']:
# Reboot the Raspberry Pi
newModeFlag = False
cmd = "sudo reboot"
subprocess.call(cmd, shell=True)
if newModeFlag:
clearDisplay()
text = "New Mode: " + menuItems[mode]
print(text)
lineOneText(text)
updateDisplay()
newModeFlag = False
except IOError:
# We get an IOError when using the ControllerResource if we don't have a controller yet,
# so in this case we just wait a second and try again after printing a message.
print('No controller found yet')
lineOneText("No Controller")
lineTwoText(" Connected")
updateDisplay()
sleep(1)
clearDisplay()
updateDisplay()
sleep(0.25)
except RobotStopException:
# This exception will be raised when the home button is pressed, at which point we should
# stop the motors.
print("stoping motors and exit to commard line")
stop_motors()
# write to display exit message
lineOneText("exited to ")
lineTwoText("command line")
updateDisplay()
sleep(1)
clearDisplay()
updateDisplay()