-
Notifications
You must be signed in to change notification settings - Fork 0
/
DriveAvoidPid.java
262 lines (207 loc) · 9.58 KB
/
DriveAvoidPid.java
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
// Simple autonomous program that drives bot forward until end of period
// or touch sensor is hit. If touched, backs up a bit and turns 90 degrees
// right and keeps going. Demonstrates obstacle avoidance and use of the
// REV Hub's built in IMU in place of a gyro. Also uses gamepad1 buttons to
// simulate touch sensor press and supports left as well as right turn.
//
// Also uses PID controller to drive in a straight line when not
// avoiding an obstacle.
//
// Use PID controller to manage motor power during 90 degree turn to reduce
// overshoot.
package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.TouchSensor;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
@Autonomous(name="Drive Avoid PID", group="Exercises")
//@Disabled
public class DriveAvoidPid extends LinearOpMode
{
DcMotor leftMotor, rightMotor;
TouchSensor touch;
BNO055IMU imu;
Orientation lastAngles = new Orientation();
double globalAngle, power = .30, correction, rotation;
boolean aButton, bButton, touched;
PIDController pidRotate, pidDrive;
// called when init button is pressed.
@Override
public void runOpMode() throws InterruptedException
{
leftMotor = hardwareMap.dcMotor.get("left_motor");
rightMotor = hardwareMap.dcMotor.get("right_motor");
leftMotor.setDirection(DcMotor.Direction.REVERSE);
leftMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
rightMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
// get a reference to REV Touch sensor.
touch = hardwareMap.touchSensor.get("touch_sensor");
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.mode = BNO055IMU.SensorMode.IMU;
parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES;
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.loggingEnabled = false;
// Retrieve and initialize the IMU. We expect the IMU to be attached to an I2C port
// on a Core Device Interface Module, configured to be a sensor of type "AdaFruit IMU",
// and named "imu".
imu = hardwareMap.get(BNO055IMU.class, "imu");
imu.initialize(parameters);
// Set PID proportional value to start reducing power at about 50 degrees of rotation.
// P by itself may stall before turn completed so we add a bit of I (integral) which
// causes the PID controller to gently increase power if the turn is not completed.
pidRotate = new PIDController(.003, .00003, 0);
// Set PID proportional value to produce non-zero correction value when robot veers off
// straight line. P value controls how sensitive the correction is.
pidDrive = new PIDController(.05, 0, 0);
telemetry.addData("Mode", "calibrating...");
telemetry.update();
// make sure the imu gyro is calibrated before continuing.
while (!isStopRequested() && !imu.isGyroCalibrated())
{
sleep(50);
idle();
}
telemetry.addData("Mode", "waiting for start");
telemetry.addData("imu calib status", imu.getCalibrationStatus().toString());
telemetry.update();
// wait for start button.
waitForStart();
telemetry.addData("Mode", "running");
telemetry.update();
sleep(1000);
// Set up parameters for driving in a straight line.
pidDrive.setSetpoint(0);
pidDrive.setOutputRange(0, power);
pidDrive.setInputRange(-90, 90);
pidDrive.enable();
// drive until end of period.
while (opModeIsActive())
{
// Use PID with imu input to drive in a straight line.
correction = pidDrive.performPID(getAngle());
telemetry.addData("1 imu heading", lastAngles.firstAngle);
telemetry.addData("2 global heading", globalAngle);
telemetry.addData("3 correction", correction);
telemetry.addData("4 turn rotation", rotation);
telemetry.update();
// set power levels.
leftMotor.setPower(power - correction);
rightMotor.setPower(power + correction);
// We record the sensor values because we will test them in more than
// one place with time passing between those places. See the lesson on
// Timing Considerations to know why.
aButton = gamepad1.a;
bButton = gamepad1.b;
touched = touch.isPressed();
if (touched || aButton || bButton)
{
// backup.
leftMotor.setPower(-power);
rightMotor.setPower(-power);
sleep(500);
// stop.
leftMotor.setPower(0);
rightMotor.setPower(0);
// turn 90 degrees right.
if (touched || aButton) rotate(-90, power);
// turn 90 degrees left.
if (bButton) rotate(90, power);
}
}
// turn the motors off.
rightMotor.setPower(0);
leftMotor.setPower(0);
}
/**
* Resets the cumulative angle tracking to zero.
*/
private void resetAngle()
{
lastAngles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES);
globalAngle = 0;
}
/**
* Get current cumulative angle rotation from last reset.
* @return Angle in degrees. + = left, - = right from zero point.
*/
private double getAngle()
{
// We experimentally determined the Z axis is the axis we want to use for heading angle.
// We have to process the angle because the imu works in euler angles so the Z axis is
// returned as 0 to +180 or 0 to -180 rolling back to -179 or +179 when rotation passes
// 180 degrees. We detect this transition and track the total cumulative angle of rotation.
Orientation angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES);
double deltaAngle = angles.firstAngle - lastAngles.firstAngle;
if (deltaAngle < -180)
deltaAngle += 360;
else if (deltaAngle > 180)
deltaAngle -= 360;
globalAngle += deltaAngle;
lastAngles = angles;
return globalAngle;
}
/**
* Rotate left or right the number of degrees. Does not support turning more than 359 degrees.
* @param degrees Degrees to turn, + is left - is right
*/
private void rotate(int degrees, double power)
{
// restart imu angle tracking.
resetAngle();
// if degrees > 359 we cap at 359 with same sign as original degrees.
if (Math.abs(degrees) > 359) degrees = (int) Math.copySign(359, degrees);
// start pid controller. PID controller will monitor the turn angle with respect to the
// target angle and reduce power as we approach the target angle. This is to prevent the
// robots momentum from overshooting the turn after we turn off the power. The PID controller
// reports onTarget() = true when the difference between turn angle and target angle is within
// 1% of target (tolerance) which is about 1 degree. This helps prevent overshoot. Overshoot is
// dependant on the motor and gearing configuration, starting power, weight of the robot and the
// on target tolerance. If the controller overshoots, it will reverse the sign of the output
// turning the robot back toward the setpoint value.
pidRotate.reset();
pidRotate.setSetpoint(degrees);
pidRotate.setInputRange(0, degrees);
pidRotate.setOutputRange(0, power);
pidRotate.setTolerance(1);
pidRotate.enable();
// getAngle() returns + when rotating counter clockwise (left) and - when rotating
// clockwise (right).
// rotate until turn is completed.
if (degrees < 0)
{
// On right turn we have to get off zero first.
while (opModeIsActive() && getAngle() == 0)
{
leftMotor.setPower(power);
rightMotor.setPower(-power);
sleep(100);
}
do
{
power = pidRotate.performPID(getAngle()); // power will be - on right turn.
leftMotor.setPower(-power);
rightMotor.setPower(power);
} while (opModeIsActive() && !pidRotate.onTarget());
}
else // left turn.
do
{
power = pidRotate.performPID(getAngle()); // power will be + on left turn.
leftMotor.setPower(-power);
rightMotor.setPower(power);
} while (opModeIsActive() && !pidRotate.onTarget());
// turn the motors off.
rightMotor.setPower(0);
leftMotor.setPower(0);
rotation = getAngle();
// wait for rotation to stop.
sleep(500);
// reset angle tracking on new heading.
resetAngle();
}
}