Drivetrain Encoders - OnBot Java
Moving the motors to a specific position, using the encoders, removes any potential inaccuracies or inconsistencies from using Elapsed Time. The focus of this section is to move the robot to a target position using encoders.
Setting up the Drivetrain Encoders
The OpMode structure below is simplified and only includes the necessary components needed to create the encoder based code.
In our example, we are addingrightmotor.setDirection(DcMotor.Direction.REVERSE);
to the code as seen below:
RUN_TO_POSITION
The first step is setting target position. To do so, add the lines leftmotor.setTargetPosition(1000);
and rightmotor.setTargetPosition(1000);
to the OpMode after the waitForStart();
command.
If we want our robot to travel a specific distance we will need to do a bit of math beforehand to calculate the TargetPosition. But for now let's start simple by setting the target position to 1000 ticks.
The next step is to set both motors to the RUN_TO_POSITION
mode. Add the lines leftmotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
and rightmotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
to your code, beneath the setTargetPosition
code lines.
Add the lines to set the power of both motors to 80% of duty cycle.
Quick Check!
Build your OpMode and give it a test. What happens once you press play? What happens if you stop the program then start it again?
STOP_AND_RESET_ENCODERS
For our demo code we will want to request our motors reset their encoders during the initialization process of the program.
Right before waitForStart();
we can add leftmotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
and rightmotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
to our OpMode.
Setting up the whileLoop
Let's say we want our program to run only for however long it takes for the motors to reach designated position. Or maybe we intend for the robot to do something else after reaching the destination. For this we will need to edit our whileLoop block!
To the whileLoop let's add the leftmotor.isBusy()
and righmotor.isBusy()
functions. This will check if the left motor and right motor are busy running to a target position. Once either motor reaches the target position the program will stop.
Build your OpMode and give it a try!
As soon as the motors hit the desired position the program will end instead of continuously run in the event they do not perfectly hit the position.
Last updated
Was this helpful?