Skip to content

Instantly share code, notes, and snippets.

@archishou
Created November 2, 2018 18:09
Show Gist options
  • Save archishou/849a9fdfdd4c043b768a5216002fe4bc to your computer and use it in GitHub Desktop.
Save archishou/849a9fdfdd4c043b768a5216002fe4bc to your computer and use it in GitHub Desktop.
public void turnRelative(double angle, Direction direction, double timeOut, int sleepTime, double kp, double ki, double kd) {
double targetAngle = tracker.imu.adjustAngle(tracker.getHeading()) + (direction.value * angle);
double acceptableError = .5;
double turnPower = .4;
double currentError = tracker.imu.adjustAngle(targetAngle - tracker.getHeading());
double prevError = 0;
double integral = 0;
double derivative;
double newPower;
double previousTime = 0;
timeoutClock.reset();
driveTrain.setClosedLoop(false);
while (opModeIsActive() && (tracker.imu.adjustAngle(Math.abs(currentError)) > acceptableError)
&& !timeoutClock.elapsedTime(timeOut, MasqClock.Resolution.SECONDS)) {
double tChange = System.nanoTime() - previousTime;
previousTime = System.nanoTime();
tChange = tChange / 1e9;
currentError = tracker.imu.adjustAngle(targetAngle - tracker.getHeading());
integral += currentError * tChange;
derivative = (currentError - prevError) / tChange;
double errorkp = currentError * kp;
double integralki = integral * ki;
double dervitivekd = derivative * kd;
newPower = (errorkp + integralki + dervitivekd);
if (Math.abs(newPower) >= 1) {newPower /= Math.abs(newPower);}
driveTrain.setPower(-newPower * turnPower, newPower * turnPower);
prevError = currentError;
this.angleLeftCover = currentError;
dash.create("TargetAngle", targetAngle);
dash.create("Heading", tracker.getHeading());
dash.create("AngleLeftToCover", currentError);
dash.create("Power: ", newPower);
dash.create("Raw Power: ", driveTrain.getPower());
dash.update();
}
driveTrain.setPower(0,0);
sleep(sleepTime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment