We've learned how to read encoder values, but how do you set where you want to go and tell the motor to go there?
Earlier, we learned about the RUN_WITHOUT_ENCODER mode for the motor. We can use another motor mode, RUN_TO_POSITION, to tell the motor to run to a specific position in ticks, like so:
Java
DcMotor motor = hardwareMap.dcmotor.get("Arm Motor");
motor.setMode(DcMotor.RunMode.RUN_TO_POSITION); // Tells the motor to run to the specific position
Tip: You can find out more about run modes at the official REV Robotics Documentation page (https://docs.revrobotics.com/duo-control/programming/using-encoder-feedback)
However, before we tell the motor to go to a position, we have to tell the motor what position to run to. Note that this value must be an integer. Let's amend the above code to do that.
Warning: Setting the motor to RUN_TO_POSITION mode before setting a target position will throw an error. Be careful not to do that!
Java
DcMotor motor = hardwareMap.dcmotor.get("Arm Motor");
int desiredPosition = 1000; // The position (in ticks) that you want the motor to move to
motor.setTargetPosition(desiredPosition); // Tells the motor that the position it should go to is desiredPosition
motor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
This code tells the motor to move to 1000 ticks, using a PID loop to control the motor's position. You can read more about PID loops here. (https://gm0.org/en/latest/docs/software/concepts/control-loops.html#pid)
We can cap the speed that the motor runs at using the following code:
Java
DcMotor motor = hardwareMap.dcmotor.get("Arm Motor");
int desiredPosition = 1000; // The position (in ticks) that you want the motor to move to
motor.setTargetPosition(desiredPosition); // Tells the motor that the position it should go to is desiredPosition
motor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
motor.setPower(0.5); // Sets the maximum power that the motor can go at
Now, let's use this information to control an arm in an OpMode.
Java