-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlueNearAutoOpSigma2016.java
More file actions
1124 lines (923 loc) · 46.3 KB
/
BlueNearAutoOpSigma2016.java
File metadata and controls
1124 lines (923 loc) · 46.3 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
/*
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted (subject to the limitations in the disclaimer below) provided that
the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of Robert Atkinson nor the names of his contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESSFOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cGyro;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
import java.text.DateFormat;
import java.util.Date;
import static com.qualcomm.robotcore.hardware.DcMotor.RunMode.RUN_WITHOUT_ENCODER;
import static org.firstinspires.ftc.teamcode.HardwareSigma2016.PUSHER_L_IN;
import static org.firstinspires.ftc.teamcode.HardwareSigma2016.PUSHER_L_OUT;
import static org.firstinspires.ftc.teamcode.HardwareSigma2016.PUSHER_R_IN;
import static org.firstinspires.ftc.teamcode.HardwareSigma2016.PUSHER_R_OUT;
import static org.firstinspires.ftc.teamcode.HardwareSigma2016.PUSHER_STOP;
import static org.firstinspires.ftc.teamcode.RedNearAutoOpSigma2016.GROUND_BRIGHTNESS_AVERAGE;
/**
* This file illustrates the concept of driving a path based on Gyro heading and encoder counts.
* It uses the common Pushbot hardware class to define the drive on the robot.
* The code is structured as a LinearOpMode
* <p>
* The code REQUIRES that you DO have encoders on the wheels,
* otherwise you would use: PushbotAutoDriveByTime;
* <p>
* This code ALSO requires that you have a Modern Robotics I2C gyro with the name "gyro"
* otherwise you would use: PushbotAutoDriveByEncoder;
* <p>
* This code requires that the drive Motors have been configured such that a positive
* power command moves them forward, and causes the encoders to count UP.
* <p>
* This code uses the RUN_TO_POSITION mode to enable the Motor controllers to generate the run profile
* <p>
* In order to calibrate the Gyro correctly, the robot must remain stationary during calibration.
* This is performed when the INIT button is pressed on the Driver Station.
* This code assumes that the robot is stationary when the INIT button is pressed.
* If this is not the case, then the INIT should be performed again.
* <p>
* Note: in this example, all angles are referenced to the initial coordinate frame set during the
* the Gyro Calibration process, or whenever the program issues a resetZAxisIntegrator() call on the Gyro.
* <p>
* The angle of movement/rotation is assumed to be a standardized rotation around the robot Z axis,
* which means that a Positive rotation is Counter Clock Wise, looking down on the field.
* This is consistent with the FTC field coordinate conventions set out in the document:
* ftc_app\doc\tutorial\FTC_FieldCoordinateSystemDefinition.pdf
* <p>
* Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
*/
@Autonomous(name = "Blue Near Auto Op Sigma 2016", group = "Sigma6710")
@Disabled
public class BlueNearAutoOpSigma2016 extends LinearOpMode {
static final double COUNTS_PER_MOTOR_REV = 1310 * 1.6; // eg: TETRIX Motor Encoder
static final double DRIVE_GEAR_REDUCTION = 1 / 1.6; // This is < 1.0 if geared UP
static final double WHEEL_DIAMETER_INCHES = 4.0; // For figuring circumference
static final double COUNTS_PER_INCH = (COUNTS_PER_MOTOR_REV * DRIVE_GEAR_REDUCTION) /
(WHEEL_DIAMETER_INCHES * 3.1415);
// These constants define the desired driving/control characteristics
// The can/should be tweaked to suite the specific robot drive train.
static final double DRIVE_SPEED = 0.9; // Nominal speed for better accuracy.
static final double P_DRIVE_COEFF = 0.05; // Larger is more responsive, but also less stable
static final double TURN_SPEED = 0.25; // Nominal half speed for better accuracy.
static final double TURN_THRESHOLD = 2; // As tight as we can make it with an integer gyro
static final double P_TURN_COEFF = 0.05; // Larger is more responsive, but also less stable
static final double MIN_TURN_SPEED = 0.15; // Larger is more responsive, but also less stable with over turn
static final double maxLeftRightSpeedDifferentialAtDrive = 0.5;
static final double WALL_APPROACHING_SPEED = 0.6;
static final double P_WALL_APPROACHING_COEFF = 0.05;
static final double LINE_DETECTION_SPEED = 0.05;
static final double WALL_TRAVELING_SPEED = 0.5;
static final double P_WALL_TRACKING_COEFF_FINE = 0.025;// Larger is more responsive, but also less stable
static final double P_WALL_TRACKING_COEFF_COARSE = 0.05;// Larger is more responsive, but also less stable
static final double TARGET_WALL_DISTANCE_FORWARD = 7; // ultrasound sensor reading for x inch away from wall
static final double TARGET_WALL_DISTANCE_BACKWARD = 8;
static final double WALL_DISTANCE_THRESHOLD = 0.5; // no need to adjust if wall distance is within range
static final int ENCODER_TARGET_THRESHOLD = 10;
static final int RED_TRESHOLD = 5;
static final int BLUE_TRESHOLD = 5;
static final double AngleThresh = 2;
static final double SpeedThresh = 0.5;
static final double PowerIncrement = 0.1;
/* Declare OpMode members. */
HardwareSigma2016 robot = null; // Additional Gyro device
// Sensor reading thread
ReadSensorsSigma2016 sensorReadingThread;
int ct0 = 0;
int ct1 = 0;
@Override
public void runOpMode() throws InterruptedException {
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
System.out.println("--BlueNear log@" + currentDateTimeString + "--");
/* -------- initializations ---------- */
/*
* Initialize the standard drive system variables.
* The init() method of the hardware class does most of the work here
*/
robot = new HardwareSigma2016();
robot.init(hardwareMap);
// start the sensor reading thread
sensorReadingThread = new ReadSensorsSigma2016(robot);
sensorReadingThread.start();
// Ensure the robot it stationary, then reset the encoders and calibrate the gyro.
robot.LeftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.RightMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
// Send telemetry message to alert driver that we are calibrating;
telemetry.addData(">", "Calibrating Gyro"); //
telemetry.update();
robot.gyro.calibrate();
// make sure the gyro is calibrated before continuing
while (!isStopRequested() && robot.gyro.isCalibrating()) {
sleep(50);
idle();
}
robot.gyro.resetZAxisIntegrator();
telemetry.addData(">", "Robot Ready."); //
telemetry.update();
// Wait for the game to start (Display Gyro value), and reset gyro before we move..
while (!isStarted()) {
telemetry.addData(">", "Robot Heading = %d", robot.gyro.getIntegratedZValue());
telemetry.update();
idle();
}
/* -------- driving to the predefined position ------- */
// Step through each leg of the path,
// Note: Reverse movement is obtained by setting a negative distance (not speed)
// Put a hold after each turn
gyroDrive(DRIVE_SPEED, 80, -42.0);// Drive FWD 81 inches along -50 degree
StopAllMotion();
if (!opModeIsActive()) {
return;
}
// Turn to -20 degree. Make the turn coeff huge so full TURN_SPEED power will be used.
gyroTurn(TURN_SPEED, -20.0, P_TURN_COEFF);
StopAllMotion();
if (!opModeIsActive()) {
return;
}
UltraSonicReachTheWall(WALL_APPROACHING_SPEED, 60, -15.0);
StopAllMotion();
if (!opModeIsActive()) {
return;
}
// 2nd line detection background light level sampling point
robot.groundbrightness_test2 = robot.lineLightSensor.red() + robot.lineLightSensor.green() + robot.lineLightSensor.blue();
// Turn to 0.0 degree with speed TURN_SPEED. Make the turn coeff huge so full TURN_SPEED power will be used.
// Otherwise the robot could stuck because only a portion of TURN_SPEED power is applied.
gyroTurn(TURN_SPEED, -5.0, P_TURN_COEFF);
StopAllMotion();
if (!opModeIsActive()) {
return;
}
// 3rd line detection background light level sampling point and calculate the average
robot.groundbrightness_test3 = robot.lineLightSensor.red() + robot.lineLightSensor.green() + robot.lineLightSensor.blue();
robot.groundbrightnessAVG = (robot.groundbrightness_test1 + robot.groundbrightness_test2 + robot.groundbrightness_test3) / 3;
/* ------ ultrasonic wall tracker + white line detection ------- */
// Drive forward to align with the wall and park at far line
WallTrackingToWhiteLine(0.4, 80, true, );
StopAllMotion();
if (!opModeIsActive()) {
return;
}
WallTrackingToWhiteLine(LINE_DETECTION_SPEED, -18, true);
StopAllMotion();
if (!opModeIsActive()) {
return;
}
// run the beacon light color detection and button pushing procedure
ColorDetectionAndButtonPushing();
if (!opModeIsActive()) {
StopAllMotion();
return;
}
// Drive backward to detect the near line
// pass the current white line without line detection
WallTrackingToWhiteLine(0.5, -40.0, false);
if (!opModeIsActive()) {
StopAllMotion();
return;
}
// detect the near white line
WallTrackingToWhiteLine(0.5, -18.0, true);
StopAllMotion();
if (!opModeIsActive()) {
return;
}
WallTrackingToWhiteLine(LINE_DETECTION_SPEED, 18.0, true);
StopAllMotion();
if (!opModeIsActive()) {
return;
}
// run the beacon light color detection and button pushing procedure
ColorDetectionAndButtonPushing();
if (!opModeIsActive()) {
StopAllMotion();
return;
}
/*------ drive to the center vortex ------*/
gyroDrive(DRIVE_SPEED, 30.00, 30.0); // 30 degree
if (!opModeIsActive()) {
StopAllMotion();
return;
}
gyroTurn(TURN_SPEED, -115, P_TURN_COEFF); // turn to 90 degree
StopAllMotion();
if (!opModeIsActive()) {
return;
}
robot.flicker.setPower(1.0);
sleep(1500);
StopAllMotion();
robot.intake.setPower(-0.5);
sleep(1000);
if (!opModeIsActive()) {
return;
}
StopAllMotion();
robot.flicker.setPower(1.0);
sleep(1500);
StopAllMotion();
gyroTurn(TURN_SPEED, -70, P_TURN_COEFF);
gyroDrive(DRIVE_SPEED, -40, -70);
StopAllMotion();
if (!opModeIsActive()) {
return;
}
// Finally, stop
StopAllMotion();
}
/**
* Method to drive on a fixed compass bearing (angle), based on encoder counts.
* Move will stop if either of these conditions occur:
* 1) Move gets to the desired position
* 2) Driver stops the opmode running.
*
* @param speed Target speed for forward motion. Should allow for _/- variance for adjusting heading
* @param distance Distance (in inches) to move from current position. Negative distance means move backwards.
* @param angle Absolute Angle (in Degrees) relative to last gyro reset.
* 0 = fwd. +ve is CCW from fwd. -ve is CW from forward.
* If a relative angle is required, add/subtract from current heading.
*/
public void gyroDrive(double power,
double distance,
double angle,
double speed) {
int newLeftTarget;
int newRightTarget;
int moveCounts;
double max;
double error;
double steer;
double leftSpeed;
double rightSpeed;
// Ensure that the opmode is still active
if (opModeIsActive()) {
// reset encoder
robot.LeftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.RightMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
// robot.backLeftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
// robot.backRightMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
// set mode
robot.LeftMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.RightMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// robot.backLeftMotor.setMode(RUN_WITHOUT_ENCODER);
// robot.backRightMotor.setMode(RUN_WITHOUT_ENCODER);
// Determine new target position, and pass to motor controller
moveCounts = (int) (distance * COUNTS_PER_INCH);
newLeftTarget = robot.LeftMotor.getCurrentPosition() + moveCounts;
newRightTarget = robot.RightMotor.getCurrentPosition() + moveCounts;
// Set Target and Turn On RUN_TO_POSITION
robot.LeftMotor.setTargetPosition(newLeftTarget);
robot.RightMotor.setTargetPosition(newRightTarget);
robot.LeftMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
robot.RightMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
// determine back motor's direction
if (distance < 0) {
if (robot.backLeftMotor.getDirection() == DcMotorSimple.Direction.FORWARD) {
robot.backLeftMotor.setDirection(DcMotorSimple.Direction.REVERSE);
} else {
robot.backLeftMotor.setDirection(DcMotorSimple.Direction.FORWARD);
}
if (robot.backRightMotor.getDirection() == DcMotorSimple.Direction.FORWARD) {
robot.backRightMotor.setDirection(DcMotorSimple.Direction.REVERSE);
} else {
robot.backRightMotor.setDirection(DcMotorSimple.Direction.FORWARD);
}
}
// start motion.
speed = Range.clip(Math.abs(speed), 0.0, 1.0);
// keep looping while we are still active, and BOTH motors are running.
while (opModeIsActive() &&
(robot.frontLeftMotor.isBusy() && robot.frontRightMotor.isBusy())) {
if (Math.abs(robot.frontLeftMotor.getCurrentPosition()
- robot.frontLeftMotor.getTargetPosition()) <= ENCODER_TARGET_THRESHOLD) {
break;
} else if (Math.abs(robot.frontRightMotor.getCurrentPosition()
- robot.frontRightMotor.getTargetPosition()) <= ENCODER_TARGET_THRESHOLD) {
break;
}
if(speed - robot.currentSpeed > SpeedThresh)
{
power += PowerIncrement;
}
else if(speed - robot.currentSpeed < -SpeedThresh)
{
power -= PowerIncrement;
}
speed = Range.clip(Math.abs(speed), 0.0, 1.0);
robot.frontLeftMotor.setPower(speed);
robot.frontRightMotor.setPower(speed);
robot.backRightMotor.setPower(speed);
robot.backLeftMotor.setPower(speed);
// adjust relative speed based on heading error.
error = getError(angle);
steer = getSteer(error, P_DRIVE_COEFF);
// if driving in reverse, the motor correction also needs to be reversed
if (distance < 0)
steer *= -1.0;
leftSpeed = speed - steer;
rightSpeed = speed + steer;
leftSpeed = Range.clip(leftSpeed,
speed - Math.abs(maxLeftRightSpeedDifferentialAtDrive * speed),
speed + Math.abs(maxLeftRightSpeedDifferentialAtDrive * speed));
rightSpeed = Range.clip(rightSpeed,
speed - Math.abs(maxLeftRightSpeedDifferentialAtDrive * speed),
speed + Math.abs(maxLeftRightSpeedDifferentialAtDrive * speed));
robot.frontLeftMotor.setPower(leftSpeed);
robot.frontRightMotor.setPower(rightSpeed);
robot.backLeftMotor.setPower(leftSpeed);
robot.backRightMotor.setPower(rightSpeed);
// Display drive status for the driver.
telemetry.addData("Err/St", "%5.1f/%5.1f", error, steer);
telemetry.addData("Targets L:R", "%7d:%7d", newLeftTarget, newRightTarget);
telemetry.addData("Actual", "%7d:%7d", robot.frontLeftMotor.getCurrentPosition(),
robot.frontRightMotor.getCurrentPosition());
telemetry.addData("Speed", "%5.2f:%5.2f", leftSpeed, rightSpeed);
telemetry.update();
}
// Turn off RUN_TO_POSITION
robot.frontLeftMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.frontRightMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
if (distance < 0) {
if (robot.backLeftMotor.getDirection() == DcMotorSimple.Direction.FORWARD) {
robot.backLeftMotor.setDirection(DcMotorSimple.Direction.REVERSE);
} else {
robot.backLeftMotor.setDirection(DcMotorSimple.Direction.FORWARD);
}
if (robot.backRightMotor.getDirection() == DcMotorSimple.Direction.FORWARD) {
robot.backRightMotor.setDirection(DcMotorSimple.Direction.REVERSE);
} else {
robot.backRightMotor.setDirection(DcMotorSimple.Direction.FORWARD);
}
}
}
}
public void StopAllMotion() {
// Stop all motion;
robot.frontLeftMotor.setPower(0);
robot.frontRightMotor.setPower(0);
robot.backLeftMotor.setPower(0);
robot.backRightMotor.setPower(0);
robot.intake.setPower(0);
robot.flicker.setPower(0);
}
/**
* Method to spin on central axis to point in a new direction.
* Move will stop if either of these conditions occur:
* 1) Move gets to the heading (angle)
* 2) Driver stops the opmode running.
*
* @param speed Desired speed of turn.
* @param angle Absolute Angle (in Degrees) relative to last gyro reset.
* 0 = fwd. +ve is CCW from fwd. -ve is CW from forward.
* If a relative angle is required, add/subtract from current heading.
*/
public void gyroTurn(double power, double angle, double turnCoeff, double expectedSpeed, double speed) {
// keep looping while we are still active, and not on heading.
while (opModeIsActive() && !onHeading(speed, angle, turnCoeff)) {
// Update telemetry & Allow time for other processes to run.
double speedControl1;
double speedControl2;
speedControl1 = robot.frontLeftMotor.getCurrentPosition();
sleep(30);
speedControl2 = robot.frontLeftMotor.getCurrentPosition();
if (speedControl1 == speedControl2)
{
speed += 0.05;
}
telemetry.update();
}
}
/**
* Method to obtain & hold a heading for a finite amount of time
* Move will stop once the requested time has elapsed
*
* @param speed Desired speed of turn.
* @param angle Absolute Angle (in Degrees) relative to last gyro reset.
* 0 = fwd. +ve is CCW from fwd. -ve is CW from forward.
* If a relative angle is required, add/subtract from current heading.
* @param holdTime Length of time (in seconds) to hold the specified heading.
*/
public void gyroHold(double speed, double angle, double holdTime) {
ElapsedTime holdTimer = new ElapsedTime();
// keep looping while we have time remaining.
holdTimer.reset();
while (opModeIsActive() && (holdTimer.time() < holdTime)) {
// Update telemetry & Allow time for other processes to run.
onHeading(speed, angle, P_TURN_COEFF);
telemetry.update();
}
// Stop all motion;
robot.frontLeftMotor.setPower(0);
robot.frontRightMotor.setPower(0);
robot.backLeftMotor.setPower(0);
robot.backRightMotor.setPower(0);
}
/**
* Perform one cycle of closed loop heading control.
*
* @param speed Desired speed of turn.
* @param angle Absolute Angle (in Degrees) relative to last gyro reset.
* 0 = fwd. +ve is CCW from fwd. -ve is CW from forward.
* If a relative angle is required, add/subtract from current heading.
* @param PCoeff Proportional Gain coefficient
* @return
*/
boolean onHeading(double speed, double angle, double PCoeff) {
double error;
double steer;
boolean onTarget = false;
double leftSpeed;
double rightSpeed;
robot.frontLeftMotor.setMode(RUN_WITHOUT_ENCODER);
robot.frontRightMotor.setMode(RUN_WITHOUT_ENCODER);
robot.backLeftMotor.setMode(RUN_WITHOUT_ENCODER);
robot.backRightMotor.setMode((RUN_WITHOUT_ENCODER));
// determine turn power based on +/- error
error = getError(angle);
if (Math.abs(error) <= TURN_THRESHOLD) {
steer = 0.0;
leftSpeed = 0.0;
rightSpeed = 0.0;
onTarget = true;
} else {
steer = getSteer(error, PCoeff);
rightSpeed = speed * steer;
if (Math.abs(rightSpeed) < MIN_TURN_SPEED) {
rightSpeed = Math.abs(rightSpeed) * MIN_TURN_SPEED / rightSpeed;
}
leftSpeed = -rightSpeed;
}
// Send desired speeds to motors.
robot.frontLeftMotor.setPower(leftSpeed);
robot.frontRightMotor.setPower(rightSpeed);
robot.backLeftMotor.setPower(leftSpeed);
robot.backRightMotor.setPower(rightSpeed);
// Display it for the driver.
telemetry.addData("Target:current", "%5.2f:5.2f", angle, robot.gyro.getIntegratedZValue());
telemetry.addData("Err/St", "%5.2f/%5.2f", error, steer);
telemetry.addData("Speed.", "%5.2f:%5.2f", leftSpeed, rightSpeed);
return onTarget;
}
/**
* getError determines the error between the target angle and the robot's current heading
*
* @param targetAngle Desired angle (relative to global reference established at last Gyro Reset).
* @return error angle: Degrees in the range +/- 180. Centered on the robot's frame of reference
* +ve error means the robot should turn LEFT (CCW) to reduce error.
*/
public double getError(double targetAngle) {
double robotError;
// calculate error in -179 to +180 range (
robotError = targetAngle - robot.gyro.getIntegratedZValue();
while (robotError > 180) robotError -= 360;
while (robotError <= -180) robotError += 360;
return robotError;
}
/**
* returns desired steering force. +/- 1 range. +ve = steer left
*
* @param error Error angle in robot relative degrees
* @param PCoeff Proportional Gain Coefficient
* @return
*/
public double getSteer(double error, double PCoeff) {
return Range.clip(error * PCoeff, -1, 1);
}
public boolean UltraSonicReachTheWall(double power,
double distance,
double angle,
double speed) {
int newLeftTarget;
int newRightTarget;
int moveCounts;
double max;
double error;
double steer;
double leftSpeed;
double rightSpeed;
double ultraSoundLevel, targetUS_Level;
double lightLevel;
// Ensure that the opmode is still active
if (opModeIsActive()) {
// reset encoder
robot.frontLeftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.frontRightMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.backLeftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.backRightMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
// set mode
robot.frontLeftMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.frontRightMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.backLeftMotor.setMode(RUN_WITHOUT_ENCODER);
robot.backRightMotor.setMode(RUN_WITHOUT_ENCODER);
// Determine new target position, and pass to motor controller
moveCounts = (int) (distance * COUNTS_PER_INCH);
newLeftTarget = robot.frontLeftMotor.getCurrentPosition() + moveCounts;
newRightTarget = robot.frontRightMotor.getCurrentPosition() + moveCounts;
// Set Target and Turn On RUN_TO_POSITION
robot.frontLeftMotor.setTargetPosition(newLeftTarget);
robot.frontRightMotor.setTargetPosition(newRightTarget);
robot.frontLeftMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
robot.frontRightMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
if (distance < 0) {
if (robot.backLeftMotor.getDirection() == DcMotorSimple.Direction.FORWARD) {
robot.backLeftMotor.setDirection(DcMotorSimple.Direction.REVERSE);
} else {
robot.backLeftMotor.setDirection(DcMotorSimple.Direction.FORWARD);
}
if (robot.backRightMotor.getDirection() == DcMotorSimple.Direction.FORWARD) {
robot.backRightMotor.setDirection(DcMotorSimple.Direction.REVERSE);
} else {
robot.backRightMotor.setDirection(DcMotorSimple.Direction.FORWARD);
}
targetUS_Level = TARGET_WALL_DISTANCE_BACKWARD + 2;
} else {
targetUS_Level = TARGET_WALL_DISTANCE_FORWARD + 2;
}
// start motion.
speed = Range.clip(Math.abs(speed), 0.0, 1.0);
robot.frontLeftMotor.setPower(speed);
robot.frontRightMotor.setPower(speed);
robot.backRightMotor.setPower(speed);
robot.backLeftMotor.setPower(speed);
// keep looping while we are still active, and BOTH motors are running.
while (opModeIsActive() &&
(robot.frontLeftMotor.isBusy() && robot.frontRightMotor.isBusy())) {
if (Math.abs(robot.frontLeftMotor.getCurrentPosition() - robot.frontLeftMotor.getTargetPosition()) <= ENCODER_TARGET_THRESHOLD) {
break;
} else if (Math.abs(robot.frontRightMotor.getCurrentPosition() - robot.frontRightMotor.getTargetPosition()) <= ENCODER_TARGET_THRESHOLD) {
break;
}
if(speed - robot.currentSpeed > SpeedThresh)
{
power += PowerIncrement;
}
else if(speed - robot.currentSpeed < -SpeedThresh)
{
power -= PowerIncrement;
}
// adjust relative speed based on heading error.
error = getError(angle);
steer = getSteer(error, P_WALL_APPROACHING_COEFF);
// if driving in reverse, the motor correction also needs to be reversed
if (distance < 0)
steer *= -1.0;
leftSpeed = speed - steer;
rightSpeed = speed + steer;
leftSpeed = Range.clip(leftSpeed,
speed - Math.abs(maxLeftRightSpeedDifferentialAtDrive * speed),
speed + Math.abs(maxLeftRightSpeedDifferentialAtDrive * speed));
rightSpeed = Range.clip(rightSpeed,
speed - Math.abs(maxLeftRightSpeedDifferentialAtDrive * speed),
speed + Math.abs(maxLeftRightSpeedDifferentialAtDrive * speed));
robot.frontLeftMotor.setPower(leftSpeed);
robot.frontRightMotor.setPower(rightSpeed);
robot.backLeftMotor.setPower(leftSpeed);
robot.backRightMotor.setPower(rightSpeed);
if (distance < 0) {
ultraSoundLevel = robot.ultra_back.getUltrasonicLevel();
} else {
ultraSoundLevel = robot.ultra_front.getUltrasonicLevel();
}
ct1++;
if (ct1 > 100) {
ct1 = 0;
System.out.println("-- wall approaching -- ultrasound level = " + ultraSoundLevel);
}
// handles abnormal ultrasonic reading
if (ultraSoundLevel == 0) {
// stop the robot
robot.frontLeftMotor.setPower(0);
robot.frontRightMotor.setPower(0);
robot.backLeftMotor.setPower(0);
robot.backRightMotor.setPower(0);
System.out.println("--BlueNear log-- abnormal -- ultrasound level=" + ultraSoundLevel);
sleep(100);
idle();
} else if (ultraSoundLevel == 255) {
// error reading. Ignore.
continue;
} else if (ultraSoundLevel <= targetUS_Level) {
System.out.println("Sigma2016 -- wall reached, ultrasound level=" + ultraSoundLevel);
// reached the wall. stop.
break;
}
}
// Turn off RUN_TO_POSITION
robot.frontLeftMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.frontRightMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
if (distance < 0) {
if (robot.backLeftMotor.getDirection() == DcMotorSimple.Direction.FORWARD) {
robot.backLeftMotor.setDirection(DcMotorSimple.Direction.REVERSE);
} else {
robot.backLeftMotor.setDirection(DcMotorSimple.Direction.FORWARD);
}
if (robot.backRightMotor.getDirection() == DcMotorSimple.Direction.FORWARD) {
robot.backRightMotor.setDirection(DcMotorSimple.Direction.REVERSE);
} else {
robot.backRightMotor.setDirection(DcMotorSimple.Direction.FORWARD);
}
}
}
return (true);
}
/**
* Method to track along a wall using an ultrasonic sensor
* Move will stop if either of these conditions occur:
* 1) Move gets to the desired distance (timeout if no white line found)
* 2) Driver stops the opmode running.
* 3) White line on the ground is detected and aligned by the light sensors
*
* @param speed Target speed for forward motion. Should allow for _/- variance for adjusting heading
* @param distance Distance (in inches) to move from current position. Negative distance means move backwards.
*/
public void WallTrackingToWhiteLine(double power,
double distance,
boolean bLineDetection,
double speed) {
int newLeftTarget;
int newRightTarget;
int moveCounts;
double error;
double steer = 0;
double leftSpeed;
double rightSpeed;
double ultraSoundLevel, angleOffset;
int lightlevel = 0;
double targetWallDistance, targetAngleOffset, angleSteer;
long curTime, timeInterval;
long previousRunTime = 0;
int expectedRunInterval = 10; // millisecond
// Ensure that the opmode is still active
if (opModeIsActive()) {
// reset encoder
robot.frontLeftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.frontRightMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.backLeftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.backRightMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
// set mode
robot.frontLeftMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.frontRightMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.backLeftMotor.setMode(RUN_WITHOUT_ENCODER);
robot.backRightMotor.setMode(RUN_WITHOUT_ENCODER);
// Determine new target position, and pass to motor controller
moveCounts = (int) (distance * COUNTS_PER_INCH);
newLeftTarget = robot.frontLeftMotor.getCurrentPosition() + moveCounts;
newRightTarget = robot.frontRightMotor.getCurrentPosition() + moveCounts;
// Set Target and Turn On RUN_TO_POSITION
robot.frontLeftMotor.setTargetPosition(newLeftTarget);
robot.frontRightMotor.setTargetPosition(newRightTarget);
robot.frontLeftMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
robot.frontRightMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
if (distance < 0) {
if (robot.backLeftMotor.getDirection() == DcMotorSimple.Direction.FORWARD) {
robot.backLeftMotor.setDirection(DcMotorSimple.Direction.REVERSE);
} else {
robot.backLeftMotor.setDirection(DcMotorSimple.Direction.FORWARD);
}
if (robot.backRightMotor.getDirection() == DcMotorSimple.Direction.FORWARD) {
robot.backRightMotor.setDirection(DcMotorSimple.Direction.REVERSE);
} else {
robot.backRightMotor.setDirection(DcMotorSimple.Direction.FORWARD);
}
targetWallDistance = TARGET_WALL_DISTANCE_BACKWARD;
} else {
targetWallDistance = TARGET_WALL_DISTANCE_FORWARD;
}
// start motion.
speed = Range.clip(Math.abs(speed), 0.0, 1.0);
robot.frontLeftMotor.setPower(speed);
robot.frontRightMotor.setPower(speed);
robot.backRightMotor.setPower(speed);
robot.backLeftMotor.setPower(speed);
if (bLineDetection)
{
// turn on line light sensor reading
sensorReadingThread.SetCenterLightSensorRead(true);
}
// keep looping while we are still active, and BOTH motors are running.
while (opModeIsActive() &&
(robot.frontLeftMotor.isBusy() && robot.frontRightMotor.isBusy())) {
if (Math.abs(robot.frontLeftMotor.getCurrentPosition() - robot.frontLeftMotor.getTargetPosition()) <= ENCODER_TARGET_THRESHOLD) {
break;
} else if (Math.abs(robot.frontRightMotor.getCurrentPosition() - robot.frontRightMotor.getTargetPosition()) <= ENCODER_TARGET_THRESHOLD) {
break;
}
if(speed - robot.currentSpeed > SpeedThresh)
{
power += PowerIncrement;
}
else if(speed - robot.currentSpeed < -SpeedThresh)
{
power -= PowerIncrement;
}
curTime = System.currentTimeMillis();
if (previousRunTime != 0)
{
timeInterval = curTime - previousRunTime;
if (timeInterval > expectedRunInterval*2)
{
System.out.println("Sigma2016 -- sensor reading thread did not run for " + timeInterval + "ms");
}
}
previousRunTime = curTime;
if (distance < 0) {
ultraSoundLevel = robot.ultra_back.getUltrasonicLevel();
} else {
ultraSoundLevel = robot.ultra_front.getUltrasonicLevel();
}
error = ultraSoundLevel - targetWallDistance;
// get angle offset of the wall
angleOffset = robot.gyro.getIntegratedZValue();
ct0++;
if (ct0 > 50) {
ct0 = 0;
System.out.println("--BlueNear log-- ultrasoniclevel=" + ultraSoundLevel + " error=" + error + " angleOffset=" + angleOffset);
}
if (ultraSoundLevel == 255) {
// error reading. Ignore.
continue;
}
// adjust angle pointing based on ultrasound reading.
if (Math.abs(error) >= WALL_DISTANCE_THRESHOLD + 2) {
// distance off by more than 2. Need steep 10 degree angle driving back to expected distance
targetAngleOffset = 0.0 - Math.signum(distance) * Math.signum(error) * 5.0;
angleSteer = targetAngleOffset - angleOffset;
steer = Math.signum(distance) * angleSteer * 0.01;
leftSpeed = speed - steer;
rightSpeed = speed + steer;
leftSpeed = Range.clip(leftSpeed, 0, Math.abs(speed));
rightSpeed = Range.clip(rightSpeed, 0, Math.abs(speed));
robot.frontLeftMotor.setPower(leftSpeed);
robot.frontRightMotor.setPower(rightSpeed);
robot.backLeftMotor.setPower(leftSpeed);
robot.backRightMotor.setPower(rightSpeed);
if (ct0 == 0) {
System.out.println("--BlueNear log-- error=" + error
+ " leftspeed=" + String.format(Double.toString(leftSpeed), "%5.2f")
+ " rightSpeed=" + String.format(Double.toString(rightSpeed), "%5.2f")
+ " curAngle=" + angleOffset
+ " targetAngle=" + targetAngleOffset);
}
} else if (Math.abs(error) >= WALL_DISTANCE_THRESHOLD + 1) {
// distance off by 1. Need mild angle driving back to expected distance
// 3.0 is the expected front/back ultrasound sensor difference
targetAngleOffset = 0.0 - Math.signum(distance) * Math.signum(error) * 2.0;
angleSteer = targetAngleOffset - angleOffset;
steer = Math.signum(distance) * angleSteer * 0.02;
leftSpeed = speed - steer;
rightSpeed = speed + steer;
leftSpeed = Range.clip(leftSpeed, 0, Math.abs(speed));
rightSpeed = Range.clip(rightSpeed, 0, Math.abs(speed));
robot.frontLeftMotor.setPower(leftSpeed);
robot.frontRightMotor.setPower(rightSpeed);
robot.backLeftMotor.setPower(leftSpeed);
robot.backRightMotor.setPower(rightSpeed);
if (ct0 == 0) {
System.out.println("--BlueNear log-- error=" + error
+ " leftspeed=" + String.format(Double.toString(leftSpeed), "%5.2f")
+ " rightSpeed=" + String.format(Double.toString(rightSpeed), "%5.2f")
+ " curAngle=" + angleOffset
+ " targetAngle=" + targetAngleOffset);
}
} else {
// distance on target. Need to keep 0 angle offset
// 3.0 is the expected front/back ultrasound sensor difference
targetAngleOffset = 0.0;
angleSteer = targetAngleOffset - angleOffset;
steer = Math.signum(distance) * angleSteer * 0.03;
leftSpeed = speed - steer;
rightSpeed = speed + steer;
leftSpeed = Range.clip(leftSpeed, 0, Math.abs(speed));
rightSpeed = Range.clip(rightSpeed, 0, Math.abs(speed));
robot.frontLeftMotor.setPower(leftSpeed);
robot.frontRightMotor.setPower(rightSpeed);
robot.backLeftMotor.setPower(leftSpeed);
robot.backRightMotor.setPower(rightSpeed);
if (ct0 == 0) {
System.out.println("--BlueNear log-- error=" + error
+ " leftspeed=" + String.format(Double.toString(leftSpeed), "%5.2f")
+ " rightSpeed=" + String.format(Double.toString(rightSpeed), "%5.2f")