Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.firstinspires.ftc.teamcode;
- import com.qualcomm.hardware.bosch.BNO055IMU;
- import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator;
- import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
- import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
- import com.qualcomm.robotcore.hardware.DcMotor;
- import com.qualcomm.robotcore.eventloop.opmode.Disabled;
- import com.qualcomm.robotcore.util.ElapsedTime;
- import org.firstinspires.ftc.robotcore.external.navigation.Acceleration;
- 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;
- import org.firstinspires.ftc.robotcore.external.navigation.Position;
- import org.firstinspires.ftc.robotcore.external.navigation.Velocity;
- import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
- import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
- import org.firstinspires.ftc.robotcore.external.ClassFactory;
- import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName;
- import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
- import org.firstinspires.ftc.robotcore.external.matrices.VectorF;
- import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
- import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
- import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
- import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackableDefaultListener;
- import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
- import java.util.ArrayList;
- import java.util.List;
- import static org.firstinspires.ftc.robotcore.external.navigation.AngleUnit.DEGREES;
- import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.XYZ;
- import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.YZX;
- import static org.firstinspires.ftc.robotcore.external.navigation.AxesReference.EXTRINSIC;
- import static org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer.CameraDirection.BACK;
- @Autonomous(name="AutonDriving", group="Skystone")
- public class AutonDriving extends LinearOpMode {
- /* Declare OpMode members. */
- SkyStoneHardware robot = new SkyStoneHardware();
- private ElapsedTime runtime = new ElapsedTime();
- String xyz = "z";
- //CONTAINS ALL METHODS AND VARIABlES TO BE EXTENDED BY OTHER AUTON CLASSES
- static final double COUNTS_PER_MOTOR_REV = 1120; // Currently: Andymark Neverest 40
- static final double COUNTS_PER_REV_ARM = 1495; //torquenado
- static final double PULLEY_DIAMETER = 1.3;
- static final double COUNTS_PER_INCH_ARM = COUNTS_PER_REV_ARM/(PULLEY_DIAMETER * Math.PI);
- static final double DRIVE_GEAR_REDUCTION = .9; // This is < 1.0 if geared UP //On OUR CENTER MOTOR THE GEAR REDUCTION IS .5
- static final double WHEEL_DIAMETER_INCHES = 3.54331; // For figuring circumference
- static final double COUNTS_PER_INCH = (COUNTS_PER_MOTOR_REV * DRIVE_GEAR_REDUCTION) /
- (WHEEL_DIAMETER_INCHES * Math.PI);
- BNO055IMU imu;
- private static final VuforiaLocalizer.CameraDirection CAMERA_CHOICE = BACK;
- private static final boolean PHONE_IS_PORTRAIT = false ;
- private static final String VUFORIA_KEY =
- "AYy6NYn/////AAABmTW3q+TyLUMbg/IXWlIG3BkMMq0okH0hLmwj3CxhPhvUlEZHaOAmESqfePJ57KC2g6UdWLN7OYvc8ihGAZSUJ2JPWAsHQGv6GUAj4BlrMCjHvqhY0w3tV/Azw2wlPmls4FcUCRTzidzVEDy+dtxqQ7U5ZtiQhjBZetAcnLsCYb58dgwZEjTx2+36jiqcFYvS+FlNJBpbwmnPUyEEb32YBBZj4ra5jB0v4IW4wYYRKTNijAQKxco33VYSCbH0at99SqhXECURA55dtmmJxYpFlT/sMmj0iblOqoG/auapQmmyEEXt/T8hv9StyirabxhbVVSe7fPsAueiXOWVm0kCPO+KN/TyWYB9Hg/mSfnNu9i9";
- // Since ImageTarget trackables use mm to specifiy their dimensions, we must use mm for all the physical dimension.
- // We will define some constants and conversions here
- private static final float mmPerInch = 25.4f;
- // the height of the center of the target image above the floor
- // Constant for Stone Target
- private static final float stoneZ = 2.00f * mmPerInch;
- // Constants for the center support targets
- // Class Members
- private OpenGLMatrix lastLocation = null;
- private VuforiaLocalizer vuforia = null;
- WebcamName webcamName = null;
- private boolean targetVisible = false;
- private float phoneXRotate = 0;
- private float phoneYRotate = 0;
- private float phoneZRotate = 0;
- @Override
- public void runOpMode() {
- robot.init(hardwareMap);
- BNO055IMU.Parameters p = new BNO055IMU.Parameters();
- p.angleUnit = BNO055IMU.AngleUnit.DEGREES;
- p.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
- p.calibrationDataFile = "BNO055IMUCalibration.json";
- p.loggingEnabled = true;
- p.loggingTag = "IMU";
- p.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator();
- imu = hardwareMap.get(BNO055IMU.class, "imu");
- imu.initialize(p);
- //side motors
- robot.fLMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- robot.fRMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- robot.fLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- //lateral motors
- robot.bLMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- robot.bRMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- robot.bLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.bRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- webcamName = hardwareMap.get(WebcamName.class, "Webcam 1");
- int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
- VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(cameraMonitorViewId);
- // VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters();
- parameters.vuforiaLicenseKey = VUFORIA_KEY;
- parameters.cameraName = webcamName;
- // Instantiate the Vuforia engine
- vuforia = ClassFactory.getInstance().createVuforia(parameters);
- // Load the data sets for the trackable objects. These particular data
- // sets are stored in the 'assets' part of our application.
- VuforiaTrackables targetsSkyStone = this.vuforia.loadTrackablesFromAsset("Skystone");
- VuforiaTrackable stoneTarget = targetsSkyStone.get(0);
- stoneTarget.setName("Stone Target");
- // For convenience, gather together all the trackable objects in one easily-iterable collection */
- List<VuforiaTrackable> allTrackables = new ArrayList<VuforiaTrackable>();
- allTrackables.addAll(targetsSkyStone);
- stoneTarget.setLocation(OpenGLMatrix
- .translation(0, 0, stoneZ)
- .multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, -90)));
- if (CAMERA_CHOICE == BACK) {
- phoneYRotate = -90;
- } else {
- phoneYRotate = 90;
- }
- // Rotate the phone vertical about the X axis if it's in portrait mode
- if (PHONE_IS_PORTRAIT) {
- phoneXRotate = 90 ;
- }
- // Next, translate the camera lens to where it is on the robot.
- // In this example, it is centered (left to right), but forward of the middle of the robot, and above ground level.
- final float CAMERA_FORWARD_DISPLACEMENT = 4.0f * mmPerInch; // eg: Camera is 4 Inches in front of robot-center
- final float CAMERA_VERTICAL_DISPLACEMENT = 8.0f * mmPerInch; // eg: Camera is 8 Inches above ground
- final float CAMERA_LEFT_DISPLACEMENT = 0; // eg: Camera is ON the robot's center line
- OpenGLMatrix robotFromCamera = OpenGLMatrix
- .translation(CAMERA_FORWARD_DISPLACEMENT, CAMERA_LEFT_DISPLACEMENT, CAMERA_VERTICAL_DISPLACEMENT)
- .multiplied(Orientation.getRotationMatrix(EXTRINSIC, YZX, DEGREES, phoneYRotate, phoneZRotate, phoneXRotate));
- /** Let all the trackable listeners know where the phone is. */
- for (VuforiaTrackable trackable : allTrackables) {
- ((VuforiaTrackableDefaultListener) trackable.getListener()).setPhoneInformation(robotFromCamera, parameters.cameraDirection);
- }
- waitForStart();
- imu.startAccelerationIntegration(new Position(), new Velocity(), 1000);
- }
- public void vuforia(VuforiaTrackables targetsSkyStone, List<VuforiaTrackable> allTrackables)
- {
- //TODO: RETURN POSITION STRING
- targetsSkyStone.activate();
- while (!isStopRequested()) {
- // check all the trackable targets to see which one (if any) is visible.
- targetVisible = false;
- for (VuforiaTrackable trackable : allTrackables) {
- if (((VuforiaTrackableDefaultListener)trackable.getListener()).isVisible()) {
- telemetry.addData("Visible Target", trackable.getName());
- targetVisible = true;
- // getUpdatedRobotLocation() will return null if no new information is available since
- // the last time that call was made, or if the trackable is not currently visible.
- OpenGLMatrix robotLocationTransform = ((VuforiaTrackableDefaultListener)trackable.getListener()).getUpdatedRobotLocation();
- if (robotLocationTransform != null) {
- lastLocation = robotLocationTransform;
- }
- break;
- }
- }
- // Provide feedback as to where the robot is located (if we know).
- if (targetVisible) {
- // express position (translation) of robot in inches.
- VectorF translation = lastLocation.getTranslation();
- telemetry.addData("Pos (in)", "{X, Y, Z} = %.1f, %.1f, %.1f",
- translation.get(0) / mmPerInch, translation.get(1) / mmPerInch, translation.get(2) / mmPerInch);
- // express the rotation of the robot in degrees.
- Orientation rotation = Orientation.getOrientation(lastLocation, EXTRINSIC, XYZ, DEGREES);
- telemetry.addData("Rot (deg)", "{Roll, Pitch, Heading} = %.0f, %.0f, %.0f", rotation.firstAngle, rotation.secondAngle, rotation.thirdAngle);
- }
- else {
- telemetry.addData("Visible Target", "none");
- }
- telemetry.update();
- }
- // Disable Tracking when we are done;
- targetsSkyStone.deactivate();
- }
- public static double counts(double inches)
- {
- double newInches = (inches - 3.7959) / 1.1239;
- return newInches;
- }
- public void normalDrive(double lpower, double rpower) {
- if (opModeIsActive()) {
- robot.fLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.bLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.bRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fLMotor.setPower(lpower);
- robot.fRMotor.setPower(rpower);
- robot.bLMotor.setPower(lpower);
- robot.bRMotor.setPower(rpower);
- }
- }
- public void turnToPosition (double target, String xyz, double topPower, double timeoutS, boolean isCorrection) {
- //stopAndReset();
- target*= -1;
- double originalAngle = readAngle(xyz);
- runtime.reset();
- double angle = readAngle(xyz); //variable for gyro correction around z axis
- double error = angle - target;
- double powerScaled = topPower;
- do {
- angle = readAngle(xyz);
- error = angle - target;
- if (!isCorrection) {
- powerScaled = topPower * (error / 180) * pidMultiplierTurning(error);
- }
- //double powerScaled = power*pidMultiplier(error);
- telemetry.addData("original angle", originalAngle);
- telemetry.addData("current angle", readAngle(xyz));
- telemetry.addData("error", error);
- telemetry.update();
- if (error > 0) {
- if (xyz.equals("z")) {
- normalDrive(powerScaled, -powerScaled);
- }
- if (xyz.equals("y")) {
- if (opModeIsActive()) {
- robot.fLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.bLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.bRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fLMotor.setPower(powerScaled);
- robot.fRMotor.setPower(powerScaled);
- robot.bLMotor.setPower(powerScaled);
- robot.bRMotor.setPower(powerScaled);
- }
- }
- } else if (error < 0) {
- if (xyz.equals("z")) {
- normalDrive(powerScaled, -powerScaled);
- }
- if (xyz.equals("y")) {
- if (opModeIsActive()) {
- robot.fLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.bLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.bRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fLMotor.setPower(powerScaled);
- robot.fRMotor.setPower(powerScaled);
- robot.bLMotor.setPower(powerScaled);
- robot.bRMotor.setPower(powerScaled);
- }
- }
- }
- } while (opModeIsActive() && ((error > .3) || (error < -0.3)) && (runtime.seconds() < timeoutS));
- normalDrive(0, 0);
- //stopAndReset();
- }
- public void stopAndReset()
- {
- robot.bRMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- robot.bLMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- robot.fRMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- robot.fLMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- robot.armExt.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- robot.armLift.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- //robot.susan.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
- //
- robot.bRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.bLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.armExt.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.armLift.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- //robot.susan.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- }
- public double pidMultiplierDriving(double error) {
- //equation for power multiplier is x/sqrt(x^2 + C)
- int C = 100;
- return Math.abs(error / Math.sqrt((error * error) + C));
- }
- public double pidMultiplierTurning(double error) {
- //equation for power multiplier is x/sqrt(x^2 + C)
- double C = .1;
- return Math.abs(error / Math.sqrt((error * error) + C));
- }
- public double readAngle(String xyz) {
- Orientation angles;
- Acceleration gravity;
- angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES);
- if (xyz.equals("x")) {
- return angles.thirdAngle;
- } else if (xyz.equals("y")) {
- return angles.secondAngle;
- } else if (xyz.equals("z")) {
- return angles.firstAngle;
- } else {
- return 0;
- }
- }
- public void encoderDrive(double inches, String direction, double timeoutS, double topPower)
- {
- stopAndReset();
- int TargetFL = 0;
- int TargetFR = 0;
- int TargetBL = 0;
- int TargetBR = 0;
- double errorFL = 0;
- double errorFR = 0;
- double errorBL = 0;
- double errorBR = 0;
- double powerFL = 0;
- double powerFR = 0;
- double powerBL = 0;
- double powerBR = 0;
- String heading = direction;
- // Ensure that the opmode is still active
- if (opModeIsActive()) {
- if(heading == "f")
- {
- TargetFL = robot.fLMotor.getCurrentPosition() + (int)( inches* COUNTS_PER_INCH);
- TargetFR = robot.fRMotor.getCurrentPosition() + (int)( inches* COUNTS_PER_INCH);
- TargetBL = robot.bLMotor.getCurrentPosition() + (int)( inches* COUNTS_PER_INCH);
- TargetBR = robot.bRMotor.getCurrentPosition() + (int)( inches* COUNTS_PER_INCH);
- }
- else if(heading == "b")
- {
- TargetFL = robot.fLMotor.getCurrentPosition() - (int)( inches* COUNTS_PER_INCH);
- TargetFR = robot.fRMotor.getCurrentPosition() - (int)( inches* COUNTS_PER_INCH);
- TargetBL = robot.bLMotor.getCurrentPosition() - (int)( inches* COUNTS_PER_INCH);
- TargetBR = robot.bRMotor.getCurrentPosition() - (int)( inches* COUNTS_PER_INCH);
- }
- else if(heading == "r")
- {
- TargetFL = robot.fLMotor.getCurrentPosition() + (int)( inches* COUNTS_PER_INCH);
- TargetFR = robot.fRMotor.getCurrentPosition() - (int)( inches* COUNTS_PER_INCH);
- TargetBL = robot.bLMotor.getCurrentPosition() - (int)( inches* COUNTS_PER_INCH);
- TargetBR = robot.bRMotor.getCurrentPosition() + (int)( inches* COUNTS_PER_INCH); //weird should be +
- }
- else if(heading == "l")
- {
- TargetFL = robot.fLMotor.getCurrentPosition() - (int)( inches* COUNTS_PER_INCH);
- TargetFR = robot.fRMotor.getCurrentPosition() + (int)( inches* COUNTS_PER_INCH);
- TargetBL = robot.bLMotor.getCurrentPosition() + (int)( inches* COUNTS_PER_INCH); // weird should be +
- TargetBR = robot.bRMotor.getCurrentPosition() - (int)( inches* COUNTS_PER_INCH);
- }
- else
- {
- telemetry.addData("not a valid direction", heading );
- }
- // Determine new target position, and pass to motor controller
- robot.fLMotor.setTargetPosition(TargetFL);
- robot.fRMotor.setTargetPosition(TargetFR);
- robot.bRMotor.setTargetPosition(TargetBR);
- robot.bLMotor.setTargetPosition(TargetBL);
- // Turn On RUN_TO_POSITION
- robot.fLMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
- robot.fRMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
- robot.bRMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
- robot.bLMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
- // reset the timeout time and start motion.
- runtime.reset();
- /*robot.fLMotor.setPower(Speed);
- robot.fRMotor.setPower(Speed);
- robot.bRMotor.setPower(Speed);
- robot.bLMotor.setPower(Speed);*/
- // keep looping while we are still active, and there is time left, and both motors are running.
- // Note: We use (isBusy() && isBusy()) in the loop test, which means that when EITHER motor hits
- // its target position, the motion will stop. This is "safer" in the event that the robot will
- // always end the motion as soon as possible.
- // However, if you require that BOTH motors have finished their moves before the robot continues
- // onto the next step, use (isBusy() || isBusy()) in the loop test.
- while (opModeIsActive() &&
- (runtime.seconds() < timeoutS) && ((robot.fLMotor.isBusy() && robot.fRMotor.isBusy()) && robot.bLMotor.isBusy() && robot.bRMotor.isBusy()))
- {
- errorFL = TargetFL - robot.fLMotor.getCurrentPosition();
- errorFR = TargetFR - robot.fRMotor.getCurrentPosition();
- errorBL = TargetBL - robot.bLMotor.getCurrentPosition();
- errorBR = TargetBR - robot.bRMotor.getCurrentPosition();
- powerFL = topPower * pidMultiplierDriving(errorFL);
- powerFR = topPower * pidMultiplierDriving(errorFR);
- powerBL = topPower * pidMultiplierDriving(errorBL);
- powerBR = topPower* pidMultiplierDriving(errorBR);
- robot.fLMotor.setPower(Math.abs(powerFL));
- robot.fRMotor.setPower(Math.abs(powerFR));
- robot.bRMotor.setPower(Math.abs(powerBL));
- robot.bLMotor.setPower(Math.abs(powerBR));
- telemetry.addData("Path1", "Running to %7d :%7d :%7d :%7d", TargetFL, TargetFR, TargetBL, TargetBR);
- telemetry.addData("Path2", "Running at %7d :%7d :%7d :%7d", robot.fLMotor.getCurrentPosition(), robot.fRMotor.getCurrentPosition(), robot.bLMotor.getCurrentPosition(), robot.bRMotor.getCurrentPosition());
- //telemetry.addData("speeds", "Running to %7f :%7f :%7f :%7f", speedfL, speedfR, speedfL, speedbR);
- telemetry.update();
- }
- // Stop all motion;
- robot.fLMotor.setPower(0);
- robot.bLMotor.setPower(0);
- robot.fRMotor.setPower(0);
- robot.bRMotor.setPower(0);
- // Turn off RUN_TO_POSITION
- robot.bRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.bLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fRMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- robot.fLMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
- // sleep(250); // optional pause after each move
- }
- stopAndReset();
- }
- public void armExtend(double inches, double topPower, double timeoutS)
- {
- stopAndReset();
- int target = robot.armExt.getCurrentPosition() + (int)(inches * COUNTS_PER_INCH_ARM);
- robot.armExt.setMode(DcMotor.RunMode.RUN_TO_POSITION);
- robot.armExt.setTargetPosition(target);
- runtime.reset();
- while(opModeIsActive() && runtime.seconds() < timeoutS && robot.armExt.isBusy())
- {
- double error = target - robot.armExt.getCurrentPosition();
- double power = topPower * pidMultiplierDriving(error);
- robot.armExt.setPower(power);
- telemetry.addData("Path1", "Running to %7d", target);
- telemetry.addData("Path2", "Running at %7d", robot.armExt.getCurrentPosition());
- telemetry.update();
- }
- robot.armExt.setPower(0);
- stopAndReset();
- }
- public void armLift(double inches, double topPower, double timeoutS)
- {
- stopAndReset();
- int target = robot.armLift.getCurrentPosition() + (int)(inches * COUNTS_PER_INCH_ARM);
- robot.armLift.setMode(DcMotor.RunMode.RUN_TO_POSITION);
- robot.armLift.setTargetPosition(target);
- runtime.reset();
- while(opModeIsActive() && runtime.seconds() < timeoutS && robot.armLift.isBusy())
- {
- double error = target - robot.armLift.getCurrentPosition();
- double power = topPower * pidMultiplierDriving(error);
- robot.armLift.setPower(power);
- telemetry.addData("Path1", "Running to %7d", target);
- telemetry.addData("Path2", "Running at %7d", robot.armLift.getCurrentPosition());
- telemetry.update();
- }
- robot.armLift.setPower(0);
- stopAndReset();
- }
- }
- /* Copyright (c) 2019 FIRST. 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 FIRST nor the names of its 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 FITNESS FOR 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.robotcore.eventloop.opmode.Disabled;
- import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
- import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
- import org.firstinspires.ftc.robotcore.external.ClassFactory;
- import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName;
- import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
- import org.firstinspires.ftc.robotcore.external.matrices.VectorF;
- import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
- import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
- import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
- import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackableDefaultListener;
- import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
- import java.util.ArrayList;
- import java.util.List;
- import static org.firstinspires.ftc.robotcore.external.navigation.AngleUnit.DEGREES;
- import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.XYZ;
- import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.YZX;
- import static org.firstinspires.ftc.robotcore.external.navigation.AxesReference.EXTRINSIC;
- import static org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer.CameraDirection.BACK;
- /**
- * This 2019-2020 OpMode illustrates the basics of using the Vuforia localizer to determine
- * positioning and orientation of robot on the SKYSTONE FTC field.
- * The code is structured as a LinearOpMode
- *
- * When images are located, Vuforia is able to determine the position and orientation of the
- * image relative to the camera. This sample code then combines that information with a
- * knowledge of where the target images are on the field, to determine the location of the camera.
- *
- * From the Audience perspective, the Red Alliance station is on the right and the
- * Blue Alliance Station is on the left.
- * Eight perimeter targets are distributed evenly around the four perimeter walls
- * Four Bridge targets are located on the bridge uprights.
- * Refer to the Field Setup manual for more specific location details
- *
- * A final calculation then uses the location of the camera on the robot to determine the
- * robot's location and orientation on the field.
- *
- * @see VuforiaLocalizer
- * @see VuforiaTrackableDefaultListener
- * see skystone/doc/tutorial/FTC_FieldCoordinateSystemDefinition.pdf
- *
- * Use Android Studio 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.
- *
- * IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as
- * is explained below.
- */
- @TeleOp(name="VuforiaTest", group ="Concept")
- //@Disabled
- public class VuforiaTest extends LinearOpMode {
- // IMPORTANT: If you are using a USB WebCam, you must select CAMERA_CHOICE = BACK; and PHONE_IS_PORTRAIT = false;
- private static final VuforiaLocalizer.CameraDirection CAMERA_CHOICE = BACK;
- private static final boolean PHONE_IS_PORTRAIT = false ;
- /*
- * IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which
- * 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function.
- * A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer
- * web site at https://developer.vuforia.com/license-manager.
- *
- * Vuforia license keys are always 380 characters long, and look as if they contain mostly
- * random data. As an example, here is a example of a fragment of a valid key:
- * ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...
- * Once you've obtained a license key, copy the string from the Vuforia web site
- * and paste it in to your code on the next line, between the double quotes.
- */
- private static final String VUFORIA_KEY =
- "AYy6NYn/////AAABmTW3q+TyLUMbg/IXWlIG3BkMMq0okH0hLmwj3CxhPhvUlEZHaOAmESqfePJ57KC2g6UdWLN7OYvc8ihGAZSUJ2JPWAsHQGv6GUAj4BlrMCjHvqhY0w3tV/Azw2wlPmls4FcUCRTzidzVEDy+dtxqQ7U5ZtiQhjBZetAcnLsCYb58dgwZEjTx2+36jiqcFYvS+FlNJBpbwmnPUyEEb32YBBZj4ra5jB0v4IW4wYYRKTNijAQKxco33VYSCbH0at99SqhXECURA55dtmmJxYpFlT/sMmj0iblOqoG/auapQmmyEEXt/T8hv9StyirabxhbVVSe7fPsAueiXOWVm0kCPO+KN/TyWYB9Hg/mSfnNu9i9";
- // Since ImageTarget trackables use mm to specifiy their dimensions, we must use mm for all the physical dimension.
- // We will define some constants and conversions here
- private static final float mmPerInch = 25.4f;
- // the height of the center of the target image above the floor
- // Constant for Stone Target
- private static final float stoneZ = 2.00f * mmPerInch;
- // Constants for the center support targets
- // Class Members
- private OpenGLMatrix lastLocation = null;
- private VuforiaLocalizer vuforia = null;
- /**
- * This is the webcam we are to use. As with other hardware devices such as motors and
- * servos, this device is identified using the robot configuration tool in the FTC application.
- */
- WebcamName webcamName = null;
- private boolean targetVisible = false;
- private float phoneXRotate = 0;
- private float phoneYRotate = 0;
- private float phoneZRotate = 0;
- @Override public void runOpMode() {
- /*
- * Retrieve the camera we are to use.
- */
- webcamName = hardwareMap.get(WebcamName.class, "Webcam 1");
- /*
- * Configure Vuforia by creating a Parameter object, and passing it to the Vuforia engine.
- * We can pass Vuforia the handle to a camera preview resource (on the RC phone);
- * If no camera monitor is desired, use the parameter-less constructor instead (commented out below).
- */
- int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
- VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(cameraMonitorViewId);
- // VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters();
- parameters.vuforiaLicenseKey = VUFORIA_KEY;
- /**
- * We also indicate which camera on the RC we wish to use.
- */
- parameters.cameraName = webcamName;
- // Instantiate the Vuforia engine
- vuforia = ClassFactory.getInstance().createVuforia(parameters);
- // Load the data sets for the trackable objects. These particular data
- // sets are stored in the 'assets' part of our application.
- VuforiaTrackables targetsSkyStone = this.vuforia.loadTrackablesFromAsset("Skystone");
- VuforiaTrackable stoneTarget = targetsSkyStone.get(0);
- stoneTarget.setName("Stone Target");
- // For convenience, gather together all the trackable objects in one easily-iterable collection */
- List<VuforiaTrackable> allTrackables = new ArrayList<VuforiaTrackable>();
- allTrackables.addAll(targetsSkyStone);
- /**
- * In order for localization to work, we need to tell the system where each target is on the field, and
- * where the phone resides on the robot. These specifications are in the form of <em>transformation matrices.</em>
- * Transformation matrices are a central, important concept in the math here involved in localization.
- * See <a href="https://en.wikipedia.org/wiki/Transformation_matrix">Transformation Matrix</a>
- * for detailed information. Commonly, you'll encounter transformation matrices as instances
- * of the {@link OpenGLMatrix} class.
- *
- * If you are standing in the Red Alliance Station looking towards the center of the field,
- * - The X axis runs from your left to the right. (positive from the center to the right)
- * - The Y axis runs from the Red Alliance Station towards the other side of the field
- * where the Blue Alliance Station is. (Positive is from the center, towards the BlueAlliance station)
- * - The Z axis runs from the floor, upwards towards the ceiling. (Positive is above the floor)
- *
- * Before being transformed, each target image is conceptually located at the origin of the field's
- * coordinate system (the center of the field), facing up.
- */
- // Set the position of the Stone Target. Since it's not fixed in position, assume it's at the field origin.
- // Rotated it to to face forward, and raised it to sit on the ground correctly.
- // This can be used for generic target-centric approach algorithms
- stoneTarget.setLocation(OpenGLMatrix
- .translation(0, 0, stoneZ)
- .multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, -90)));
- //
- // Create a transformation matrix describing where the phone is on the robot.
- //
- // NOTE !!!! It's very important that you turn OFF your phone's Auto-Screen-Rotation option.
- // Lock it into Portrait for these numbers to work.
- //
- // Info: The coordinate frame for the robot looks the same as the field.
- // The robot's "forward" direction is facing out along X axis, with the LEFT side facing out along the Y axis.
- // Z is UP on the robot. This equates to a bearing angle of Zero degrees.
- //
- // The phone starts out lying flat, with the screen facing Up and with the physical top of the phone
- // pointing to the LEFT side of the Robot.
- // The two examples below assume that the camera is facing forward out the front of the robot.
- // We need to rotate the camera around it's long axis to bring the correct camera forward.
- if (CAMERA_CHOICE == BACK) {
- phoneYRotate = -90;
- } else {
- phoneYRotate = 90;
- }
- // Rotate the phone vertical about the X axis if it's in portrait mode
- if (PHONE_IS_PORTRAIT) {
- phoneXRotate = 90 ;
- }
- // Next, translate the camera lens to where it is on the robot.
- // In this example, it is centered (left to right), but forward of the middle of the robot, and above ground level.
- final float CAMERA_FORWARD_DISPLACEMENT = 4.0f * mmPerInch; // eg: Camera is 4 Inches in front of robot-center
- final float CAMERA_VERTICAL_DISPLACEMENT = 8.0f * mmPerInch; // eg: Camera is 8 Inches above ground
- final float CAMERA_LEFT_DISPLACEMENT = 0; // eg: Camera is ON the robot's center line
- OpenGLMatrix robotFromCamera = OpenGLMatrix
- .translation(CAMERA_FORWARD_DISPLACEMENT, CAMERA_LEFT_DISPLACEMENT, CAMERA_VERTICAL_DISPLACEMENT)
- .multiplied(Orientation.getRotationMatrix(EXTRINSIC, YZX, DEGREES, phoneYRotate, phoneZRotate, phoneXRotate));
- /** Let all the trackable listeners know where the phone is. */
- for (VuforiaTrackable trackable : allTrackables) {
- ((VuforiaTrackableDefaultListener) trackable.getListener()).setPhoneInformation(robotFromCamera, parameters.cameraDirection);
- }
- // WARNING:
- // In this sample, we do not wait for PLAY to be pressed. Target Tracking is started immediately when INIT is pressed.
- // This sequence is used to enable the new remote DS Camera Preview feature to be used with this sample.
- // CONSEQUENTLY do not put any driving commands in this loop.
- // To restore the normal opmode structure, just un-comment the following line:
- // waitForStart();
- // Note: To use the remote camera preview:
- // AFTER you hit Init on the Driver Station, use the "options menu" to select "Camera Stream"
- // Tap the preview window to receive a fresh image.
- targetsSkyStone.activate();
- while (!isStarted()) {
- // check all the trackable targets to see which one (if any) is visible.
- targetVisible = false;
- for (VuforiaTrackable trackable : allTrackables) {
- if (((VuforiaTrackableDefaultListener)trackable.getListener()).isVisible()) {
- telemetry.addData("Visible Target", trackable.getName());
- targetVisible = true;
- // getUpdatedRobotLocation() will return null if no new information is available since
- // the last time that call was made, or if the trackable is not currently visible.
- OpenGLMatrix robotLocationTransform = ((VuforiaTrackableDefaultListener)trackable.getListener()).getUpdatedRobotLocation();
- if (robotLocationTransform != null) {
- lastLocation = robotLocationTransform;
- }
- break;
- }
- }
- // Provide feedback as to where the robot is located (if we know).
- //TODO: ADD STATEMENTS W/ POSITION VALUE CORRESPONDING TO SKYSTONE POSITION
- if (targetVisible) {
- // express position (translation) of robot in inches.
- VectorF translation = lastLocation.getTranslation();
- telemetry.addData("Pos (in)", "{X, Y, Z} = %.1f, %.1f, %.1f",
- translation.get(0) / mmPerInch, translation.get(1) / mmPerInch, translation.get(2) / mmPerInch);
- // express the rotation of the robot in degrees.
- Orientation rotation = Orientation.getOrientation(lastLocation, EXTRINSIC, XYZ, DEGREES);
- telemetry.addData("Rot (deg)", "{Roll, Pitch, Heading} = %.0f, %.0f, %.0f", rotation.firstAngle, rotation.secondAngle, rotation.thirdAngle);
- }
- else {
- telemetry.addData("Visible Target", "none");
- }
- telemetry.update();
- }
- telemetry.addData("stopped", "stopped");
- telemetry.update();
- sleep(2500);
- // Disable Tracking when we are done;
- targetsSkyStone.deactivate();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement