Make a Motor Move to a Position
All of the motors we use have encoders, sensors that can precisely measure movement, built into them. We can use that to move a motor to a specific position.
First, we need to configure our motor to work this way. We should also reset the encoder count when we start our OpMode - otherwise, we’ll run into odd behavior when we start the robot multiple times.
Add the following to the init method, after the line you already added to set your motor variable.
myMotor.setTargetPosition(0);
myMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
myMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
This tells the motor to go to 0 ticks on the encoder, resets the encoder count to 0, and then puts the motor in an automatic positional control mode.
On the drivetrains we’re working with, one complete rotation of a wheel is about 1000 encoder ticks.
In your loop method, add the following to tell your motor to spin the wheel around approximately one complete rotation.
myMotor.setTargetPosition(1000);
Build and run your program. If you try to move the wheel by hand, you’ll feel the robot fight against you and keep the wheel where it’s supposed to be. Adjust your program to make the wheel rotate faster or slower and watch how it responds.
Once you’re done with this, remove the setTargetPosition line and replace RUN_TO_POSITION with RUN_USING_ENCODER, and remove the other setMode line.