-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
549 lines (419 loc) · 17.4 KB
/
main.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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# Initializes display and controls, shows menus
# Put .py files you want to run in /creations/ and they will show up in the menu
# Look at demo.py for an example of how to make a compatible creation
from machine import Pin, I2C, ADC
from time import sleep
import os
import framebuf
#TRUE = Throw all errors, crashes
#FALSE = Display errors on the device screen instead and attempt to continue
# Keep true while debugging to get info like line numbers
# Keep false for users so that one bug in a creation doesn't crash the whole device
debug = False
#Stop any previous music PWM
#from buzzer_music import music
#music().stop()
#Display wrapper class - better than display specific draw instructions...
class display:
def __init__(self, display_type):
self.display_type = display_type
self.skippedFrames = 0
if (self.display_type == "SSD1306 Monochrome"):
width = 128
height = 64
#Put the GP pins you use for SDA and SCL here
i2c = I2C(0,sda=Pin(4),scl=Pin(5),freq=600000) #40000
from ssd1306 import SSD1306_I2C
self.oled = SSD1306_I2C(width,height,i2c)
self.width = self.oled.width
self.height = self.oled.height
elif (self.display_type == "Pimoroni Pico Display"):
import picodisplay
self.oled = picodisplay
self.width = self.oled.get_width()
self.height = self.oled.get_height()
picodisplay_buffer = bytearray(self.width * self.height * 2) # 2-bytes per pixel (RGB565)
self.oled.init(picodisplay_buffer)
picodisplay_buffer = None
self.oled.set_backlight(1.0)
self.fill(0)
elif (self.display_type == "Waveshare SSD1327 16 Bit Grey"):
from ssd1327 import WS_OLED_128X128
oled_i2c = I2C(0, sda=Pin(16), scl=Pin(17),freq=3000000) #2300000
self.oled = WS_OLED_128X128(oled_i2c, addr=int(hex(oled_i2c.scan()[0])))
print("OLED I2C Address : " + hex(oled_i2c.scan()[0]).upper()) # Print the I2C device address in the command line
print("OLED I2C Configuration: " + str(oled_i2c))
self.width = self.oled.width
self.height = self.oled.height
def fill_rect(self, x, y, width, height, color):
if (self.display_type == "SSD1306 Monochrome"):
if (color > 0):
color = 1
self.oled.fill_rect(x,y,width,height,color)
elif (self.display_type == "Pimoroni Pico Display"):
c = round(255*color)
self.oled.set_pen(c, c, c)
self.oled.rectangle(x,y,width,height)
elif (self.display_type == "Waveshare SSD1327 16 Bit Grey"):
self.oled.fill_rect(x,y,width,height,round(15*color))
else:
#...since you can add support for other screens
pass
def show(self):
if (self.display_type == "SSD1306 Monochrome" or self.display_type == "Waveshare SSD1327 16 Bit Grey"):
try:
self.oled.show()
except OSError as e:
self.skippedFrames = self.skippedFrames + 1
elif (self.display_type == "Pimoroni Pico Display"):
self.oled.update()
def fill(self, color):
if (self.display_type == "SSD1306 Monochrome"):
if (color > 0):
color = 1
self.oled.fill(color)
elif (self.display_type == "Pimoroni Pico Display"):
c = round(255*color)
self.oled.set_pen(c, c, c)
self.oled.clear()
elif (self.display_type == "Waveshare SSD1327 16 Bit Grey"):
self.oled.fill(round(15*color))
def text(self, text, x, y, color=1):
if (self.display_type == "SSD1306 Monochrome"):
self.oled.text(text, x, y)
elif (self.display_type == "Pimoroni Pico Display"):
c = round(255*color)
self.oled.set_pen(c, c, c)
self.oled.text(text, x, y, 0, 1)
elif (self.display_type == "Waveshare SSD1327 16 Bit Grey"):
self.oled.text(text, x, y, round(15*color))
def pixel(self, x, y, color):
if (self.display_type == "SSD1306 Monochrome"):
if (color > 0):
color = 1
self.oled.pixel(x, y, color)
elif (self.display_type == "Pimoroni Pico Display"):
c = round(255*color)
self.oled.set_pen(c, c, c)
self.oled.pixel(x, y)
elif (self.display_type == "Waveshare SSD1327 16 Bit Grey"):
self.oled.pixel(x, y, round(15*color))
def blit(self, buffer, x, y, key, palette=None):
if (self.display_type == "SSD1306 Monochrome"):
if (key > 0):
key = 1
self.oled.blit(buffer, x, y, key)
elif (self.display_type == "Waveshare SSD1327 16 Bit Grey"):
if (palette == None):
self.oled.blit(buffer, x, y, round(15*key))
else:
self.oled.blit(buffer, x, y, round(15*key), palette)
def line(self, x1, y1, x2, y2, color):
if (self.display_type == "SSD1306 Monochrome"):
if (color > 0):
color = 1
self.oled.line(x1, y1, x2, y2, color)
def scroll(self, x, y):
if (self.display_type == "SSD1306 Monochrome" or self.display_type == "Waveshare SSD1327 16 Bit Grey"):
self.oled.scroll(x, y)
def invert(self, i):
self.oled.invert(i)
def stroke_rect(self, x, y, width, height, color):
if (self.display_type == "SSD1306 Monochrome"):
if (color > 0):
color = 1
self.oled.stroke_rect(x,y,width,height,color)
elif (self.display_type == "Pimoroni Pico Display"):
c = round(255*color)
self.oled.set_pen(c, c, c)
self.oled.stroke_rect(x,y,width,height)
elif (self.display_type == "Waveshare SSD1327 16 Bit Grey"):
self.oled.stroke_rect(x,y,width,height,round(15*color))
#self.fill_rect(0+x,0+y,width,1,color)
#self.fill_rect(width-1+x,0+y,1,height,color)
#self.fill_rect(0+x,height-1+y,width,1,color)
#self.fill_rect(0+x,0+y,1,height,color)
def ellipse(self, x, y, xr, yr, col, fill=False, quadrantBits=0xF):
self.oled.ellipse(x, y, xr, yr, round(15*col), fill, quadrantBits)
def poly(self, x, y, coords, col, fill=False):
self.oled.poly(x, y, coords, round(15*col), fill)
def rotate(self, rot):
self.oled.rotate(rot)
def contrast(self, c):
self.oled.contrast(c)
def poweron(self):
self.oled.poweron()
def poweroff(self):
self.oled.poweroff()
#display = display("SSD1306 Monochrome")
#display = display("Pimoroni Pico Display") #WIP
display = display("Waveshare SSD1327 16 Bit Grey")
#Class for creations to use input
class controller:
def __init__(self, analogs=[], buttons=[], joyscale=1000, deadzone=10, picodisplay=None):
self.joystick = False
self.joyscale = joyscale
self.deadzone = deadzone
if (len(analogs) >= 2):
#Use analogs as joystick
self.joyX = analogs[0]
self.joyY = analogs[1]
self.joystick = True
self.joyCenter = (self.joyX.read_u16(),self.joyY.read_u16())
self.buttons = buttons
self.usePicodisplay = False
if (not (picodisplay is None)):
self.usePicodisplay = True
self.picodisplay = picodisplay
def readJoystick(self):
if (self.joystick):
x = self.joyX.read_u16() - self.joyCenter[0]
y = self.joyY.read_u16() - self.joyCenter[1]
x = x / self.joyscale
y = y / self.joyscale
outsideDeadzone = False
if (abs(x) > self.deadzone or abs(y) > self.deadzone):
outsideDeadzone = True
return (-x, y, outsideDeadzone)
else:
#Emulate non existant joystick with buttons
if (not self.readButton(0)):
return (0, -20, True)
elif (not self.readButton(1)):
return (0, 20, True)
elif (not self.readButton(2)):
return (-20, 0, True)
elif (not self.readButton(3)):
return (20, 0, True)
return (0,0,False)
def readButton(self, buttonNumber):
if (self.usePicodisplay):
if (buttonNumber == 0):
if (display.oled.is_pressed(display.oled.BUTTON_A)):
return True
else:
return False
elif (buttonNumber == 1):
if (display.oled.is_pressed(display.oled.BUTTON_B)):
return True
else:
return False
elif (buttonNumber == 2):
if (display.oled.is_pressed(display.oled.BUTTON_X)):
return True
else:
return False
elif (buttonNumber == 3):
if (display.oled.is_pressed(display.oled.BUTTON_Y)):
return True
else:
return False
else:
if (buttonNumber >= len(self.buttons)):
return False
return not self.buttons[buttonNumber].value()
controller = controller(analogs=[
ADC(Pin(27)),
ADC(Pin(26))
], buttons=[
Pin(14, machine.Pin.IN, machine.Pin.PULL_UP),
Pin(15, machine.Pin.IN, machine.Pin.PULL_UP)
])
#controller = controller(picodisplay=display)
creations = os.listdir('/creations/')
#Remove non .py files from creations array
i = 0
while (i < len(creations)):
if (not (".py" in creations[i])):
creations.pop(i)
else:
i = i + 1
creation = None
mainMenu = True
cursor = 0
frame = 0
names = []
thumbnails = []
#Get name+thumbnail for each creation
i = 0
for filename in creations:
#Attempt Import
exec("try:\n from creations."+creations[i].replace('.py','')+" import description\nexcept ImportError:\n pass")
try:
description
except NameError:
#Unsuccessful
names.append(creations[i].replace('.py',''))
thumbnails.append(None)
else:
#Successful
if (hasattr(description, 'name')):
names.append(description.name)
else:
names.append(creations[i].replace('.py',''))
if (hasattr(description, 'thumbnail')):
thumbnails.append(framebuf.FrameBuffer(description.thumbnail, 32, 32, framebuf.MONO_HLSB))
else:
thumbnails.append(None)
del description
i = i + 1
#Handle errors thrown by creations so that they can be dropped back to main menu
#Disable by setting debug = True
def errorHan(e, customMessage=None):
global debug
global mainMenu
global creation
global display
if (debug):
raise e
return
e = repr(e)
print(e)
print("Set debug = True in main.py to throw exceptions...")
print("Skipped frames: " + str(display.skippedFrames))
#Split exception string into screen width strings
n = int(display.width/8)
o = []
while e:
o.append(e[:n])
e = e[n:]
display.fill(0)
for i in range(len(o)):
display.text(o[i],0,i*8)
if (not (customMessage is None)):
o = []
while customMessage:
o.append(customMessage[:n])
customMessage = customMessage[n:]
for j in range(len(o)):
display.text(o[j],0,((i+1)*8)+(j*8))
display.show()
sleep(5)
creation = None
mainMenu = True
#Function to load into the selected creation
def onSelect():
global creations
global cursor
global creation
global mainMenu
global display
global config
print("onSelect")
display.fill(0)
display.text("Loading %s..." % creations[cursor].replace('.py',''), 0, 0)
display.show()
if (controller.readButton(0) == 1 and controller.readButton(1) == 1):
return
autorunFile = open('autorun', 'w')
autorunFile.write(str(cursor))
autorunFile.close()
exec("try:\n from creations.%s import creation\nexcept Exception:\n pass" % creations[cursor].replace('.py',''))
mainMenu = False
try:
creation = creation(display, controller)
except Exception as e:
errorHan(e, "Error while trying to create object from expected 'creation' class in the file")
#Try to auto open previous creation
autorunFile = open('autorun', 'r')
c = autorunFile.read()
if (not (c == '')):
cursor = int(c)
if (cursor >= len(creations)):
cursor = len(creations)-1
onSelect()
autorunFile.close()
moveCooldown = 0
buttonCooldowns = [0,0]
buttonCooldown = 5
heldDown = 0
led = Pin(25, Pin.OUT) #Blink led to show it's alive
display.contrast(255)
while True:
frame = frame + 1
led.toggle()
buttonCooldowns[0] = max(0, (buttonCooldowns[0] - 1))
buttonCooldowns[1] = max(0, (buttonCooldowns[1] - 1))
#Hold down both buttons for 30 frames to exit to main menu
if (controller.readButton(0) and controller.readButton(1)):
heldDown = heldDown + 1
if (heldDown > 30):
heldDown = 0
buttonCooldowns[0] = 15
buttonCooldowns[1] = 15
print("Skipped frames: " + str(display.skippedFrames))
if (not(creation is None)):
try:
creation.close()
except Exception:
pass
del creation
creation = None
mainMenu = True
autorunFile = open('autorun', 'w')
autorunFile.write(str(""))
autorunFile.close()
else:
heldDown = 0
if (mainMenu):
#Move cursor
if (moveCooldown > 0):
moveCooldown = moveCooldown - 1
joy = controller.readJoystick()
if (joy[2] and (moveCooldown <= 0) and (abs(joy[1]) > abs(joy[0]))):
moveCooldown = 5
if (joy[1] > 0):
#up
cursor = cursor + 1
if (cursor >= len(creations)):
cursor = 0
else:
#down
cursor = cursor - 1
if (0 > cursor):
cursor = len(creations)-1
#Detect button press
select = False
if (buttonCooldowns[0] == 0):
if (controller.readButton(0)):
buttonCooldowns[0] = buttonCooldown
select = True
display.fill(0)
if (not (thumbnails[cursor] is None)):
for thumbx in range(5):
for thumby in range(5):
#display.blit(thumbnails[cursor],display.width-40,16,0)
display.blit(thumbnails[cursor],-32 + thumbx*32 + (frame % 32),-32 + thumby*32 + (frame % 32),0)
#List files in creations folder
ySpacing = 11
i = 0
#Calculate scroll position of text
linesPerScreen = 11
scroll = 0
if (len(creations) > linesPerScreen):
if (cursor > 2):
scroll = (cursor-2)*ySpacing
#Stop scroll at the bottom
if ((len(creations)-1) - cursor < 3):
scroll = (len(creations)-linesPerScreen)*ySpacing
scroll = 0 - scroll
for i in range(len(creations)):
display.fill_rect(8,3+(ySpacing*i)-1+scroll,len(names[i])*8+2,ySpacing,0)
display.text(names[i],9,3+(ySpacing*i)+scroll)
#Selection Border
if (cursor == i):
display.stroke_rect(8,3+(ySpacing*i)-1+scroll,len(names[i])*8+2,ySpacing,1)
i = i + 1
#Scroll bar
display.stroke_rect(0,0,4,display.height,1)
position = cursor/max((len(creations)-1),1)
display.fill_rect(1,round(position*display.height)-round(display.height/8),2,round(display.height/4),1)
display.show()
if (select):
onSelect()
else:
#Run loaded creation
try:
creation.tick()
except Exception as e:
errorHan(e)