-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3676 lines (2980 loc) · 133 KB
/
main.py
File metadata and controls
3676 lines (2980 loc) · 133 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
#region Initialization of Constants/Global Variables
global g
g = -9.81 # Use for flywheel speed calculator
global field_length
field_length = 356 # CM
global turret_theta_vel
turret_theta_vel = 0
global RAD_TO_DEG
RAD_TO_DEG = 180 / math.pi
global DEG_TO_RAD
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)
global programming_chassis
programming_chassis = True
if not programming_chassis:
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)
inertial = Inertial(Ports.PORT8)
flywheel_motor = Motor(Ports.PORT20, GearSetting.RATIO_6_1, False)
else:
# left_motor_a = Motor(Ports.PORT20, GearSetting.RATIO_18_1, False)
# left_motor_b = Motor(Ports.PORT10, GearSetting.RATIO_18_1, False)
# 7.5, 2.75
# right_motor_a = Motor(Ports.PORT11, GearSetting.RATIO_18_1, True)
# right_motor_b = Motor(Ports.PORT1, GearSetting.RATIO_18_1, True)
inertial = Inertial(Ports.PORT18)
left_motor_a = Motor(Ports.PORT1, GearSetting.RATIO_18_1, False)
left_motor_b = Motor(Ports.PORT11, GearSetting.RATIO_18_1, False)
right_motor_a = Motor(Ports.PORT10, GearSetting.RATIO_18_1, True)
right_motor_b = Motor(Ports.PORT20, GearSetting.RATIO_18_1, True)
flywheel_motor = Motor(Ports.PORT19, GearSetting.RATIO_6_1, False)
indexer_limit_switch = DigitalIn(brain.three_wire_port.c)
turret_limit_switch = DigitalIn(brain.three_wire_port.d)
turret_motor = Motor(Ports.PORT14, GearSetting.RATIO_36_1, False)
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 (disc signatures if we want to autoamtically sense discs, blue and red signatures for the red ang blue goals)
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_GOAL = Signature(3, 7243, 8689, 7966,-701, 107, -297,3, 0)
vision__BLUE_GOAL = 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_GOAL,
vision__BLUE_GOAL, vision__DISK)
DISC_SIGNATURES = [vision__DISC, vision__BRIGHT_DISK]
#endregion
#region Misc/Helper Functions/Classes
def argmax(arr):
return arr.index(max(arr))
def interpolate(x, x1, x2, y1, y2):
return (x - x1) * (y2 - y1) / (x2 - x1) + y1
def closest_angle(ang):
# Turn via the shortest path
while ang > 180:
ang -= 360
while ang < -180:
ang += 360
return ang
def std(_list):
if len(_list) == 0:
return 0
# Standard deviation
_mean = sum(_list) / len(_list)
_sum = 0
for i in _list:
_sum += (i - _mean)**2
return math.sqrt(_sum / len(_list))
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 test_drivetrain():
### Tests to see how long it takes for the drivetrain to overheat (reach 55 deg.)
t = Timer()
t.reset()
val = 0
while True:
r.set_target_state({
# Make it so that the robot is constantly rotating
"override_theta_velocity" : 100,
})
if t.value() > 5 + val:
# Display the temperature
print(t.value(), left_motor_a.temperature(), right_motor_a.temperature(), left_motor_b.temperature(), right_motor_b.temperature())
val = t.value()
if left_motor_a.temperature() >= 55 or right_motor_a.temperature() >= 55 or left_motor_b.temperature() >= 55 or right_motor_b.temperature() >= 55:
# When any of the motors overheat (reach 55 deg. C) then stop the program and display how long it took to overheat
print("It took ", t.value(), "seconds to overheat!")
# Stop the robot from rotating
r.set_target_state({
"theta" : r.theta
})
return
# Reset theta function
def reset_robot_theta():
r.set_target_state({
"theta" : 0
})
r.total_theta = 0
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
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
def check_intersection(line1, line2):
# line1 and line2 are tuples of 4 points (x1, y1, x2, y2)
# returns True if they intersect, False otherwise
# Prevents divide by 0 error
if (line1[2] - line1[0]) == 0:
line1[2] += 0.0001
line1[0] -= 0.0001
if (line2[2] - line2[0]) == 0:
line2[2] += 0.0001
line2[0] -= 0.0001
# get the slope and y-intercept of each line
m1 = (line1[3] - line1[1]) / (line1[2] - line1[0])
m2 = (line2[3] - line2[1]) / (line2[2] - line2[0])
b1 = line1[1] - m1 * line1[0]
b2 = line2[1] - m2 * line2[0]
# if the slopes are equal, they are parallel and don't intersect
if m1 == m2:
return False
# find the point of intersection
x = (b2 - b1) / (m1 - m2)
y = m1 * x + b1
# check if the point of intersection is within the line segments
if x > max(line1[0], line1[2]) or x < min(line1[0], line1[2]):
return False
if x > max(line2[0], line2[2]) or x < min(line2[0], line2[2]):
return False
if y > max(line1[1], line1[3]) or y < min(line1[1], line1[3]):
return False
if y > max(line2[1], line2[3]) or y < min(line2[1], line2[3]):
return False
return True
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
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: " + 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 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
#endregion
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. It should be called before every other function for the robot
'''
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.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)
turret_motor.set_stopping(HOLD)
# 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(),
})
brain.screen.draw_rectangle(10, 10, 10, 10, Color.WHITE)
if programming_chassis:
gps.set_origin(190, 60, MM)
else:
gps.set_origin(288, 30, MM)
inertial.calibrate()
average_gps_values = []
initial_x_positions = []
initial_y_positions = []
initial_theta_positions = []
if gps.installed():
init_timer = Timer()
init_timer.reset()
init_time = 2
while init_timer.value() < init_time:
initial_x_positions.append(gps.x_position(DistanceUnits.CM))
initial_y_positions.append(gps.y_position(DistanceUnits.CM))
initial_theta_positions.append(gps.heading())
wait(0.02, SECONDS)
r.initial_x_field = float(sum(initial_x_positions) / len(initial_x_positions))
r.initial_y_field = float(sum(initial_y_positions) / len(initial_y_positions))
# self.initial_x_field, self.initial_y_field = rotate_vector_2d(self.initial_x_field, self.initial_y_field, self.gps_theta_on_robot * DEG_TO_RAD)
r.initial_theta_field = float(sum(initial_theta_positions) / len(initial_theta_positions)) - r.gps_theta_on_robot # The + 90 is because the gps is 90 deg off of the robot
print("From calibrating, average positions are: ", r.initial_x_field, r.initial_y_field, r.initial_theta_field)
print("Stds are: ", std(initial_x_positions), std(initial_y_positions), std(initial_theta_positions))
while inertial.is_calibrating():
wait(0.05, SECONDS)
# 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("...")
#region Object Trajectory Prediction
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
#endregion
#region GUI elements for brain screen
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)
#endregion
class Robot:
'''
This is the big-boy robot class, this is the class that controls the robot, there is a lot of stuff here
'''
#region Variables relating to orientation/positions/etc
total_theta = 0
initial_theta_field = 0
max_velocity: float
max_acceleration: float
previous_x_encoders_relative = 0
previous_y_encoders_relative = 0
previous_x_gps_field = 0
previous_y_gps_field = 0
x_encoders_relative = 0
y_encoders_relative = 0
gps_theta_on_robot = 0 # gps is 90 deg to the right from the center of the robot
delta_x_encoders_field = 0
delta_y_encoders_field = 0
delta_x_encoders_relative = 0
delta_y_encoders_relative = 0
x_encoders_field = 0
y_encoders_field = 0
delta_x_gps_relative = 0
delta_y_gps_relative = 0
delta_x_gps_field = 0
delta_y_gps_field = 0
theta_field = 0
x_gps_relative = 0
y_gps_relative = 0
initial_x_field = 0
initial_y_field = 0
initial_theta_field = 0
x_from_gps = 0
y_from_gps = 0
# variance of gps, we got this number through experimentation (sted ^ 2)
gps_variance = 8
x_position_variance = 8
y_position_variance = 8
predicted_position = 0
#endregion
#region Flywheel Variables
turret_initial_position = -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_avg_speed = 0
previous_flywheel_avg_speed = 0
previous_flywheel_error = 0
integral_term_flywheel = 0
previous_flywheel_speed = 0
flywheel_speed = 0
flywheel_height_from_ground_IN = -99999
flywheel_motor_error = 0
limit_switch_active = True
flywheel_motor_average_output = 0
average_target_flywheel_output = 0
flywheel_angle_offset = 0
target_goal = None
flywheel_speed_levels = [
0,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
100,
]
distance_speed_maps = {
0: 0,
100 : 0,
1000 : 50,
}
turret_theta_range = 40
#endregion
#region Drivetrain Variables
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
#endregion
#region Timers
flywheel_recovery_timer = Timer()
intake_timer = Timer()
# 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()
# endregion
#region States/State Trackers
previous_update_time: float = 0
target_reached = False
update_loop_delay = 0.006 # 10 ms
autonomous_speed: float = 48
running_autonomous = False
# State dictionary will hold ALL information about the robot
'''
x_pos: X position of the robot
y_pos: Y position of the robot