-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup_feb_24.py
More file actions
3398 lines (2803 loc) · 120 KB
/
Copy pathbackup_feb_24.py
File metadata and controls
3398 lines (2803 loc) · 120 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
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import time
from vex import *
from math import cos, sin, pi, sqrt, atan2
# Constants initialization
global g
g = -9.81 # Use for flywheel speed calculator
global RAD_TO_DEG
global DEG_TO_RAD
RAD_TO_DEG = 180 / math.pi
DEG_TO_RAD = math.pi / 180
global robot_debug_mode
robot_debug_mode = False
global recording_autonomous
recording_autonomous = False
global r2o2
r2o2 = math.sqrt(2) / 2
# *###### INITIATLIZATION OF PERIPHERALS
brain = Brain()
controller_1 = Controller(PRIMARY)
controller_2 = Controller(PARTNER)
left_motor_a = Motor(Ports.PORT10, GearSetting.RATIO_18_1, False)
left_motor_b = Motor(Ports.PORT9, GearSetting.RATIO_18_1, False)
right_motor_a = Motor(Ports.PORT1, GearSetting.RATIO_18_1, True)
right_motor_b = Motor(Ports.PORT2, GearSetting.RATIO_18_1, True)
flywheel_motor_1 = Motor(Ports.PORT19, GearSetting.RATIO_6_1, False)
flywheel_motor_2 = Motor(Ports.PORT11, GearSetting.RATIO_6_1, True)
indexer_limit_switch = DigitalIn(brain.three_wire_port.c)
inertial = Inertial(Ports.PORT8)
roller_and_intake_motor_1 = Motor(Ports.PORT4, GearSetting.RATIO_36_1, False)
roller_and_intake_motor_2 = Motor(Ports.PORT5, GearSetting.RATIO_36_1, False)
roller_and_intake_motor = MotorGroup(
roller_and_intake_motor_1, roller_and_intake_motor_2)
roller_optical = Optical(Ports.PORT6)
indexer = Pneumatics(brain.three_wire_port.a)
expansion = Pneumatics(brain.three_wire_port.b)
flywheel_status_light = Led(brain.three_wire_port.h)
gps = Gps(Ports.PORT12)
# Vision signatures
vision__DISC = Signature(1, 6911, 8133, 7522, -6787, -5937, -6362, 1.3, 0)
vision__BRIGHT_DISK = Signature(2, 217, 491, 354, -7169, -6839, -7004, 3, 0)
vision__RED = Signature(3, 7243, 8689, 7966,-701, 107, -297,3, 0)
vision__BLUE = Signature(4, -1985, 1, -992,1981, 6665, 4323,1.4, 0)
vision__DISK = Signature(5, 1905, 2299, 2102,-4017, -3641, -3829,2.5, 0)
vision = Vision(Ports.PORT7, 50, vision__DISC, vision__BRIGHT_DISK, vision__RED,
vision__BLUE, vision__DISK)
DISC_SIGNATURES = [vision__DISC, vision__BRIGHT_DISK]
def set_debug_value(_value):
one_controller_mode = _value
def start_recording_mode_for_autonomous(_value):
print("I HAVE BEEN PRESSED AND MY VAL IS", _value)
global recording_autonomous
recording_autonomous = _value
def print_state_nicely(state):
# print white space so we can see easier when coping and pasting
print("[\n")
# nicely format the state dictionary
for s in state:
_str = ""
_str += "\n {"
for key in s:
_str += "\n " + "\"" + key + "\"" + ": " + str(s[key]) + ","
_str += "\n },"
print(_str)
print("]\n")
def get_angle_to_object(pos_1, pos_2):
'''
RETURNS IN DEGREES
'''
# If the passed in objects are GameObjects then change the pos's into a tuple of x,y values
if type(pos_1) == GameObject:
pos_1 = (pos_1.x, pos_1.y)
if type(pos_2) == GameObject:
pos_2 = (pos_2.x, pos_2.y)
ang = atan2(pos_2[0] - pos_1[0], pos_2[1] - pos_1[1]) * RAD_TO_DEG
if ang > 180:
ang -= 360
if ang < -180:
ang += 360
return ang
# 53
def init():
'''
This function will initialize every subsystem with constants that wont change throughout the competition,
it will set driver controlled motors to break mode, start spinning motors that use the "set_velocity()" function,
and initialize our gyroscope
'''
left_motor_a.set_stopping(BRAKE)
right_motor_a.set_stopping(BRAKE)
left_motor_b.set_stopping(BRAKE)
right_motor_b.set_stopping(BRAKE)
flywheel_motor_1.spin(FORWARD, 0, VOLT)
flywheel_motor_2.spin(FORWARD, 0, VOLT)
left_motor_a.set_velocity(0, PERCENT)
right_motor_a.set_velocity(0, PERCENT)
left_motor_b.set_velocity(0, PERCENT)
right_motor_b.set_velocity(0, PERCENT)
left_motor_a.spin(FORWARD)
# These wheels are reversed so that they spin ccw instead of cw for forward
right_motor_a.spin(REVERSE)
left_motor_b.spin(FORWARD)
# These wheels are reversed so that they spin ccw instead of cw for forward
right_motor_b.spin(REVERSE)
# Set the optical light power
# roller_optical.set_light_power(100)
# roller_optical.object_detect_threshold(0)
expansion.close()
t = Timer()
t.reset()
# Set our target states (this initializes drone_mode on and gusing gps is determined if the gps is plugged in)
r.set_target_state({
"drone_mode": False,
"using_gps": gps.installed(),
})
gps.set_origin(84, 200, MM)
# Wait for the gyro to settle, if it takes more then 10 seconds then close out of the loop
# When the gyro sensor inits, it reads some value for the Z rotation, this is less than a few degrees, but i don't like it
while (inertial.gyro_rate(ZAXIS) != 0 and t.value() < 10):
print("Waiting for gyro to init...")
wait(0.1, SECONDS)
# Rumlbed the control to indicate to the driver (and me) that the robot is ready to run
controller_1.rumble("...")
class GameObject:
'''
If we want to introduce game object (like say the goal or barriers), we have have to robot look up important information about the game object
'''
def __init__(self, x_pos, y_pos):
self.x_pos = x_pos
self.y_pos = y_pos
def f(*args):
'''
This function replaces the f-strings that are in python 3.8 (i think) and above, but aren't in python 3.6, which is what the brain uses
'''
message = ""
for arg in args:
if type(arg) != str:
arg = str(arg)
message += " " + arg
return message
def sign(num):
'''
Returns the sign of the number
'''
if num == 0:
return 1.0
return abs(num) / num
def clamp(num, _max, _min):
'''
Clamps the number between the max and min
'''
if _max < _min:
_max, _min = _min, _max
return max(min(num, _max), _min)
def rotate_vector_2d(x, y, theta):
'''
Rotates a vector by theta degrees
'''
x_old = x
x = x * math.cos(theta) - y * math.sin(theta)
y = x_old * math.sin(theta) + y * math.cos(theta)
return x, y
def getPathOnXYFunction(funcs, delta_t=0.01):
'''
Funcs - An array of two functions, the first one will return the x component of an objects trajectory at time point t, and the second will return the y component of an objects trajectory at time point t. It will run these function until the object hits the ground.
Returns an array of x positions, y positions, and the time it took to hit the ground
'''
# Get the x and y functions out of the functions array so that we can more intuitively refer to them
xFunc = funcs[0]
yFunc = funcs[1]
# Start off time at delta time (no need to compute the x and y positions at t=0 because we know that it will start on the group)
t = delta_t
# Create an array to store the x and y positions, initialize the array with the x and y positions at the first timestep
x = [xFunc(t)]
y = [yFunc(t)]
# Run the functions until the y x of the function is less than 0 (the object has hit the ground)
while y[-1] > 0 and x[-1] > 0:
t += delta_t
x.append(xFunc(t))
y.append(yFunc(t))
return x, y, t
def returnXYFuncs(theta, v_i):
'''This will return two funcions, for the x and y component of the objects path, depending upon the objects initial launch angle (theta) and initial velocity'''
return returnXFunc(theta, v_i), returnYFunc(theta, v_i)
def returnXFunc(theta, v_i):
'''Returns the x component of the objects trajecotry using the following formula'''
return lambda t: cos(theta) * v_i * t
def returnYFunc(theta, v_i):
''' Returns the x component of the objects trajecotry using the following formula.'''
# NOTE: This function is assuming that you live on earth and thus acceleration is gravity
return lambda t: (1/2 * g * t * t + sin(theta) * v_i * t)
def calculateRequiredInitialVelocityToPassThroughAPoint(coords):
'''
This is a function that I derived in order to calculate the required initial velocity for an object to pass through a point.
The formula for this equation is:
______________________________________________
| ____________________________________
v_i = |-2gy + __|((2gy)^2 - (4 * -(g^2 * x^2)))
|----------------------------------------------
__| 2
'''
x = coords[0]
y = coords[1]
w = 2 * g * y
q = - g * g * x * x
squareRoot = math.sqrt((w * w) - (4 * q))
expression = (-w + squareRoot)/2
return (math.sqrt(expression))
def getThetaForPathToHitPoint(v_i, point, sizeOfPoint=0.05):
'''This function, when given the initial velocity required, will output the angle needed to shoot at.
point - point we want to hit
sizeOfPoint - the tolerance at which we can hit the point, at extereme initial velocities, this needs to be very high
'''
theta = 0
go = True
iterations = 0
minimum_distance = 0
# How this works is that it plots the trajectory of the object at changing angles of being shot, and it returns the correct angle once it is hit. This can be optimized by a hell of a lot and there is probably a mathetmatical formula that you can use to get the correct point in like 2 milliseconds buuuuuuut I already made a very good formula before that used a lot of brain power and Winter break was almost over so I settled on this solution, if I need to run this formula on a system that actually shoots things and is very time sensitive, then I will fix this, but otherwise there isn't a need to fix it.
while go:
new_theta_1 = theta + (pi / 4) * 2 ** (-iterations)
new_theta_2 = theta - (pi / 4) * 2 ** (-iterations)
# Run a simulation for both new theta angles
_x, _y, _t = getPathOnXYFunction(returnXYFuncs(new_theta_1, v_i))
minimum_distance_theta_1 = float('inf')
# Find the point that is the closest to the point we want to hit
for x, y in zip(_x, _y):
distance = math.sqrt((x - point[0])**2 + (y - point[1])**2)
minimum_distance_theta_1 = min(minimum_distance_theta_1, distance)
_x, _y, _t = getPathOnXYFunction(returnXYFuncs(new_theta_2, v_i))
minimum_distance_theta_2 = float('inf')
# Find the point that is the closest to the point we want to hit
for x, y in zip(_x, _y):
distance = math.sqrt((x - point[0])**2 + (y - point[1])**2)
minimum_distance_theta_2 = min(minimum_distance_theta_2, distance)
# If the new theta angles are closer to the point we want to hit, then we will use those angles
if minimum_distance_theta_1 < minimum_distance_theta_2:
minimum_distance = minimum_distance_theta_1
theta = new_theta_1
else:
minimum_distance = minimum_distance_theta_2
theta = new_theta_2
# If the point we want to hit is within the tolerance, then we are done
if minimum_distance < sizeOfPoint:
go = False
iterations += 1
if iterations > 50:
print("Reached maximimum iterations!", theta)
go = False
return theta
def getViForPathToHitPoint(theta, point, sizeOfPoint=0.05):
'''This function, when given the initial velocity required, will output the angle needed to shoot at.
point - point we want to hit
sizeOfPoint - the tolerance at which we can hit the point, at extereme initial velocities, this needs to be very high
'''
vi = 0
go = True
iterations = 0
minimum_distance = 0
max_vi = 8.65
delta_time = 0.001
hit_time = 0
# How this works is that it plots the trajectory of the object at changing angles of being shot, and it returns the correct angle once it is hit. This can be optimized by a hell of a lot and there is probably a mathetmatical formula that you can use to get the correct point in like 2 milliseconds buuuuuuut I already made a very good formula before that used a lot of brain power and Winter break was almost over so I settled on this solution, if I need to run this formula on a system that actually shoots things and is very time sensitive, then I will fix this, but otherwise there isn't a need to fix it.
while go:
new_vi_1 = vi + (max_vi / 2) * 2 ** (-iterations)
new_vi_2 = vi - (max_vi / 2) * 2 ** (-iterations)
# Run a simulation for both new vi angles
_x, _y, _t = getPathOnXYFunction(
returnXYFuncs(theta, new_vi_1), delta_time)
minimum_distance_vi_1 = float('inf')
hit_time_vi_1 = 0
# Find the point that is the closest to the point we want to hit
for x, y in zip(_x, _y):
distance = math.sqrt((x - point[0])**2 + (y - point[1])**2)
minimum_distance_vi_1 = min(minimum_distance_vi_1, distance)
if minimum_distance_vi_1 == distance:
hit_time_vi_1 = (_x.index(x) + 1) * delta_time
_x, _y, _t = getPathOnXYFunction(
returnXYFuncs(theta, new_vi_2), delta_time)
minimum_distance_vi_2 = float('inf')
hit_time_vi_2 = 0
# Find the point that is the closest to the point we want to hit
for x, y in zip(_x, _y):
distance = math.sqrt((x - point[0])**2 + (y - point[1])**2)
minimum_distance_vi_2 = min(minimum_distance_vi_2, distance)
if minimum_distance_vi_2 == distance:
hit_time_vi_2 = (_x.index(x) + 1) * delta_time
# If the new vi angles are closer to the point we want to hit, then we will use those angles
if minimum_distance_vi_1 < minimum_distance_vi_2:
minimum_distance = minimum_distance_vi_1
vi = new_vi_1
hit_time = hit_time_vi_1
else:
minimum_distance = minimum_distance_vi_2
vi = new_vi_2
hit_time = hit_time_vi_2
# If the point we want to hit is within the tolerance, then we are done
if minimum_distance < sizeOfPoint:
go = False
iterations += 1
if iterations > 20:
go = False
return vi, hit_time
class Button:
'''
Basic button class, params:
- name: Name of button (gets displayed in the middle of the button)
- x: x position of the top-left corner of the button on the screen
- y: y position of the top-left corner of the button on the screen
- w: width of the button (px)
- h: height of the button (px)
- color: color of the button
- call_back: function that gets called when the button is pressed
- args: arguments that get passed to the functions
'''
needs_to_render = True
def __init__(self, name = "", x = 0, y = 0, w = 0, h = 0, color = 0, call_back = None, *args):
self.name = name
self.x = x
self.y = y
self.w = w
self.h = h
self.color = color
self.call_back = call_back
self.args = args
def render(self):
# Draw a rectangle on the screen
brain.screen.draw_rectangle(self.x, self.y, self.w, self.h, self.color)
# Figure out the x and y position of the text so that it gets centered, the max() function prevents the text from going outside the left edge of the box
x_position_of_text = max((self.x + self.w / 2) - (len(self.name) * 5), self.x)
y_position_of_text = max(self.y + self.h / 2 + 5 , self.y)
brain.screen.print_at(self.name, x=x_position_of_text, y=y_position_of_text, opaque = False)
def set_callback(self, function):
self.call_back = function
# If we do something like button() then it will run the callback function
def __call__(self):
if self.call_back != None:
# If self is a variable in the call_back function then pass self as the button
self.call_back(*self.args)
class Text:
'''
Basic text class, params:
- name: Name of text (gets displayed in the middle of the text)
- x: x position of the top-left corner of the text-box on the screen
- y: y position of the top-left corner of the text-box on the screen
- w: width that the text-box occupates
- h: height that the text-box occupates
- color: color of the text fill
- call_back: function that gets called periodically to update the text name (function must return a string)
- args: arguments that get passed to the functions
'''
def __init__(self, name = "", x = 0, y = 0, w = 0, h = 0, color = 0, call_back = None, *args):
self.name = name
self.x = x
self.y = y
self.w = w
self.h = h
self.color = color
self.call_back = call_back
self.args = args
def render(self):
# If there is a call back function, then call it and set the name to the return value, else the name will never change
if self.call_back != None:
self.name = self.call_back(*self.args)
brain.screen.draw_rectangle(self.x, self.y, self.w, self.h, self.color)
# Figure out the x and y position of the text so that it gets centered, the max() function prevents the text from going outside the left edge of the box
x_position_of_text = max((self.x + self.w / 2) - (len(self.name) * 5), self.x)
y_position_of_text = max(self.y + self.h / 2 + 5 , self.y)
brain.screen.print_at(self.name, x=x_position_of_text, y=y_position_of_text, opaque = False)
def __call__(self):
# this does literllay nothing
if self.call_back != None:
self.name = self.call_back(*self.args)
class Switch:
# A switch class is the same as a button class, but instead it has states and each state calls another function
# so for example, the switch class changes it colors when it changes states
needs_to_render = True
def __init__(self, name = [], x = 0, y = 0, w = 0, h = 0, color = [], states = [], *args):
self.name = name
self.x = x
self.y = y
self.w = w
self.h = h
if type(states) == list:
self.states = states
else:
self.states = [states] * len(args[0])
self.current_state = 0
self.colors = color
self.args = args
def render(self):
brain.screen.draw_rectangle(self.x, self.y, self.w, self.h, self.colors[self.current_state])
# Figure out the x and y position of the text so that it gets centered, the max() function prevents the text from going outside the left edge of the box
x_position_of_text = max(self.x + self.w / 2 - len(self.name[self.current_state]) * 5, self.x)
y_position_of_text = max(self.y + self.h / 2 + 5 , self.y)
brain.screen.print_at(self.name[self.current_state], x=x_position_of_text, y=y_position_of_text, opaque = False)
def set_states(self, states):
self.states = states
def set_state(self, state):
self.current_state = state
def change_state(self):
self.current_state = (self.current_state + 1) % len(self.name)
def run_state(self):
try:
self.states[self.current_state](*[arg[self.current_state] for arg in self.args])
except IndexError:
print("index error lmao")
def __call__(self):
'''
Whenever the switch gets pressed, change the sate of the switch (which changes the name and the color), and run the new call-back function
'''
self.change_state()
self.run_state()
class GUI:
'''
What I want this class to do it to make a way for the drivers to interact with the brain screen and see some status
things like if the motors are too hot, or if there is any self-diagnosed problem. I also want people to be able to select
from the brain what team we're on.
Brain screen dimensions: 480 x 240 pizels. Top left is (0,0)
Each character in a string is 10 x 10 pixels
'''
elements = []
pages = []
page_num = 0
previous_brain_screen_state = False
def __init__(self):
Thread(self.update_forever)
def add_page(self, elements = []):
self.pages.append(elements)
def add_element(self, element, page_num = None):
if page_num == None:
self.elements.append(element)
return
self.pages[page_num].append()
def update(self):
# If the brain has been pressed ANYWHERE
if brain.screen.pressing() and not self.previous_brain_screen_state:
# X and y positions of where the finger pressed
x, y = brain.screen.x_position(), brain.screen.y_position()
for element in self.pages[self.page_num]:
# Figure out if the finger press was inside the bound-box of an element
if (x - element.x) > 0 and (x - element.x) < element.w and (y-element.y) > 0 and (y - element.y) < element.h:
# Run the callback function of the element as a thread (so the rest of the code DOES NOT stop)
Thread(element.__call__)
self.previous_brain_screen_state = brain.screen.pressing()
def render(self):
'''
Renders each element of the gui
'''
brain.screen.clear_screen()
if len(self.pages) > 0:
for element in self.pages[self.page_num]:
element.render()
brain.screen.render()
def set_page(self, page_num):
self.page_num = page_num
self.elements = self.pages[page_num - 1]
def update_forever(self):
while True:
self.update()
self.render()
wait(0.05, SECONDS)
class Vector:
'''
Vector class I wrote because basic python lists are lame, this is as slow as normal python, should be ideally replaced with numpy arrays
'''
def __init__(self, data):
self.data = data
def __add__(self, other):
assert len(other) == len(self.data)
return [other[i] + self.data[i] for i in range(len(self.data))]
def __sub__(self, other):
assert len(other) == len(self.data)
return Vector([other[i] - self.data[i] for i in range(len(self.data))])
def __getitem__(self, key):
return self.data[key]
def __len__(self):
return len(self.data)
def __repr__(self):
return "Vector:\t" + repr(self.data)
class PID:
'''
Your standard PID controller (look up on wikipedia if you don't know what it is)
'''
previous_value = None
integral_error = 0
derivative_error = 0
proportional_error = 0
def __init__(self, kP, kI, kD):
self.kP = kP
self.kI = kI
self.kD = kD
def update(self, _value, delta_time=None):
'''
Updates the PID controller with the new value, optional delta_time parameter means you can use this for non-constant time steps
'''
if delta_time != None:
self.integral_error += _value * delta_time
else:
self.integral_error += _value
if self.previous_value != None:
# Compute derivative term
self.derivative_error = _value - self.previous_value
self.previous_value = _value
return _value * self.kP + self.integral_error * self.kI + self.derivative_error * self.kD
def set_constants(self, kP, kI, kD):
'''
Updates the constants of the PID controller
'''
self.kP = kP
self.kI = kI
self.kD = kD
def reset(self):
'''
Resets the PID controller
'''
self.integral_error = 0
self.previous_value = None
class Robot:
'''
This is the big-boy robot class, this is the class that controls the robot, there is a lot of stuff here
'''
# * ORIENTATION/POSITION VARIABLES
total_theta = 0
theta_offset = 0
max_velocity: float
max_acceleration: float
previous_x_from_encoders = 0
previous_y_from_encoders = 0
previous_x_from_gps = 0
previous_y_from_gps = 0
total_x_from_encoders = 0
total_y_from_encoders = 0
gps_theta_on_robot = 90 # gps is 90 deg to the right from the center of the robot
# * FLYWHEEL
length: float = 38.1
x_from_gps = 0
y_from_gps = 0
# Set the offset for the flywheel from the center of the robot
flywheel_offset_x = 0
flywheel_offset_y = 0
flywheel_angle = 45 * DEG_TO_RAD
flywheel_1_avg_speed = 0
flywheel_2_avg_speed = 0
previous_flywheel_1_avg_speed = 0
previous_flywheel_2_avg_speed = 0
previous_flywheel_1_error = 0
previous_flywheel_2_error = 0
integral_term_flywheel_1 = 0
integral_term_flywheel_2 = 0
previous_flywheel_speed = 0
flywheel_speed = 0
flywheel_height_from_ground_IN = -99999
flywheel_motor_1_PID = PID(2, 0, 0)
flywheel_motor_2_PID = PID(2, 0, 0)
flywheel_motor_1_error = 0
flywheel_motor_2_error = 0
running_autonomous = False
# * DRIVETRAIN
previous_update_time: float = 0
drivetrain_gear_ratio = 18
wheel_max_rpm: float = 200
wheel_diameter_CM: float = 8.255
# In order to get this, it is ticks for the specific gear ratio we're using divided by the circumeference of our wheel
wheel_distance_CM_to_TICK_coefficient: float = (drivetrain_gear_ratio / 6 * 300) / (math.pi * wheel_diameter_CM) * 0.47
# * PID controllers
flywheel_motor_1_average_output = 0
flywheel_motor_2_average_output = 0
autonomous_speed: float = 0.48
# * MISC
update_loop_delay = 0.00 # 10 ms
# Used to keep track of time in auto and driver mode respectively, use it for nicely logging data, can be used during either modes for end game/pathfinding rules
autonomous_timer = Timer()
driver_controlled_timer = Timer()
target_reached = False
position_tolerance = 3 # tolerance to target position in cm
orientation_tolerance = 8 # tolerance to target orientation in degrees
# From 0,0 (which is the center of the field). Dimensions were got from page 89 on: https://content.vexrobotics.com/docs/2022-2023/vrc-spin-up/VRC-SpinUp-Game-Manual-2.2.pdf
red_goal = GameObject(143, 143)
blue_goal = GameObject(-143, -143)
flywheel_speed_levels = [
0,
33,
34,
round(35.0000000),
36,
37,
38,
39,
40,
41,
42,
43,
45,
46,
100,
]
# State dictionary will hold ALL information about the robot
'''
x_pos: X position of the robot
y_pos: Y position of the robot
'''
state = {
# Orientation
"x_pos" : 0,
"y_pos" : 0,
"x_gps" : 0,
"y_gps" : 0,
"x_enc" : 0,
"y_enc" : 0,
"theta" : 0,
"theta_vel" : 0,
"time" : 0,
"autonomous_speed" : 0,
# override velocities
"override_velocity_x" : 0,
"override_velocity_y" : 0,
"override_velocity_theta" : 0,
# Roller stuff
"roller_state" : "none",
"auto_roller" : False,
"roller_speed" : 0,
"roller_spin_for" : 0,
"roller_and_intake_motor_1_done" : True,
"roller_and_intake_motor_2_done" : True,
# Intake
"auto_intake" : False,
"disc_in_intake" : False,
# Actuators
"flywheel_speed" : 0,
"intake_speed" : 0,
"shoot_disc" : 0,
# expansion
"launch_expansion" : False,
# Commands
"using_gps" : False,
"is_shooting": False,
"slow_mode" : False,
"drone_mode" : False,
"autonomous" : False,
"flywheel_torque" : 0,
"disc_shot" : False,
"flywheel_1_torque" : 0,
"flywheel_2_torque" : 0,
"is_shooting" : False,
}
intake_timer = Timer()
target_state = {
"x_pos" : None,
"y_pos" : None,
"theta" : None,
}
all_states = []
delta_time = 0
is_red_team = False
save_states = False
path = [
# Initial state of the robot
{
"set_x" : 0,
"set_y" : 0,
"set_theta" : 0,
"override_velocity_x" : None,
"override_velocity_y" : None,
"override_velocity_theta" : None,
"drone_mode" : True,
},
]
total_updates = 0
flywheel_recovery_timer = Timer()
average_target_flywheel_output_1 = 0
average_target_flywheel_output_2 = 0
def __init__(self):
# what our max velocity "should" be (can go higher or lower)
self.max_velocity = ((self.wheel_max_rpm / 60) *
math.pi * 2 * self.wheel_diameter_CM / math.sqrt(2))
# This number in the divisor means it will speedup/slow down in that many seeconds
self.max_acceleration = 2 * self.max_velocity / 0.00001
# Set origin of the gps
gps.set_origin(0,0)
# Thsee next few lines just make sure that the state system works, and saves and initial state that we return to when the autonomous mode ends
self.initial_state = self.state.copy()
self.set_target_state(self.state)
self.previous_state = self.state
# There are two init methods, this init initializes the class, the other init method we call to initlize the robot
def init(self):
'''
Different than the Robot()__init__ dunder that gets called when the robot is made, this is a manual initialization that
starts the update loop and turns on the robot
'''
# Set heading based on gps
if self.using_gps:
# For some reason, the gps returns nan, just wait until it doesn't return nan
while str(gps.heading()) == "nan":
print("Waiting for gps", gps.heading())
time.sleep(0.1)
# Actual theta of the robot from the field is the gps heading minus the angle of the gps on the robot (90 deg in this instance)
self.theta_offset = gps.heading() - self.gps_theta_on_robot # The + 90 is because the gps is 90 deg off of the robot
self.set_target_state(self.state)
self.previous_state = self.state
Thread(self.update_loop)
self.flywheel_recovery_timer.reset()
def update_loop(self):
'''
Runs the self.update command every self.update_loop_delay seconds forever
'''
while True:
self.update()
wait(self.update_loop_delay, SECONDS)
def update(self):
'''
This is a VERY important function, it should be called once every [0.1 - 0.01] seconds (the faster the better, especially for controls)
It updates the robot's position based off of the encoders and the gyro
'''
self.delta_time = (getattr(time, "ticks_ms")() / 1000) - (self.previous_state["time"])
# prevent divide by zero
if self.delta_time == 0:
return
# If we want to save the states of the the robot (which will allow us to do cool things such as recording our matches and replaying our momvements, this must be turned to true)
if self.save_states:
self.all_states.append(self.state)
# Update the previous state before doing state estimation
self.previous_state = self.state.copy()
# Estimate our current position
self.estimate_state()
# All controls for movement, pid control for robot
self.position_update()
# All of the updates needed for the flywheel, including pid control
self.flywheel_update()
# All of code for roller, including auto roller
self.roller_update()
# All of the code and checks for the intake, allows for auto intake and manual control
self.intake_update()
# Run all the code needed for the expansion
self.expansion_update()
# Update all status indicators
self.status_update()
def position_update(self):
'''
Updates the position of the robot
'''
# Find out how much the robot needs to move in each direction
delta_x = 0
delta_y = 0
delta_theta = 0
# If the target state does not exist then we don't need to move in that direction
if self.target_state["x_pos"] != None:
delta_x = self.target_state["x_pos"] - self.x_pos
if self.target_state["y_pos"] != None:
delta_y = self.target_state["y_pos"] - self.y_pos
if self.target_state["theta"] != None:
delta_theta = self.target_state["theta"] - self.theta
# Turn via the shortest path
if delta_theta > 180:
delta_theta -= 360
elif delta_theta < -180:
delta_theta += 360
orientation_tolerance = 9
position_tolerance = 15
# Make sqrt the delta theta, so that the tolerance is not linear but a sqrt relationshup
delta_theta = math.sqrt(abs(delta_theta)) * sign(delta_theta)