Encoders
Encoders, like servos, have a broad definition, but in this context, encoders tell you how much a motor rotates, allowing you to calculate important values, such as the distance traveled.
Creating Encoder Objects
The Encoder IDs function exactly like the IDs from the XRPMotors and the XRPServos, they are here to differentiate Encoder objects from each other. Luckily for you, like the XRP objects, the Encoders have already been created in the XRPDrivetrain!
Encoders for the most part are generally built into motors for convenience, but here you have to declare them yourself.
// The XRP has onboard encoders that are hardcoded
// to use DIO pins 4/5 and 6/7 for the left and right
private final Encoder m_leftEncoder = new Encoder(4, 5);
private final Encoder m_rightEncoder = new Encoder(6, 7);Configuring Encoders
In your XRPDrivetrain, you might find these lines of code. The four variables on top are just using the specs and dimensions of your XRPMotor and its wheels to estimate the amount the wheels would have rotated every time the encoder updates.
private static final double kGearRatio =
(30.0 / 14.0) * (28.0 / 16.0) * (36.0 / 9.0) * (26.0 / 8.0); // 48.75:1
private static final double kCountsPerMotorShaftRev = 12.0;
private static final double kCountsPerRevolution = kCountsPerMotorShaftRev * kGearRatio; // 585.0
private static final double kWheelDiameterInch = 2.3622; // 60 mm
//
m_leftEncoder.setDistancePerPulse((Math.PI * kWheelDiameterInch) / kCountsPerRevolution);
m_rightEncoder.setDistancePerPulse((Math.PI * kWheelDiameterInch) / kCountsPerRevolution);Encoders, every so often, update their values, so the user can do important calculations involving them. This is what these lines are for.
According to the pre-made variables, the encoders update their values 1440 times an entire revolution. The calculations inside the method is simply dividing the circumference by the distance.
Important Encoder Methods
There are other things we can configure on an encoder. Here are some important methods you can use for them.
Resetting the Encoder
If you want to reset the encoder's distance, you can call the reset() method onto the encoder. It is important to call this at the beginning of your code, to make sure your encoders won't give some improper values.
Getting Encoder Distance
One of the most useful pieces of data you can get from an encoder that's so important it needs its own subcategory is the distance traveled. This is accessed through the getDistance() method. This method returns a double and has no parameters. Here is an example with both the m_leftEncoder and m_rightEncoder:
To make your distance calculations as accurate as possible, you should get the average distance between both encoders.
There are other pieces of data that encoders can return, such as the motor's velocity (using the distance traveled per pulse), if the motor stopped, and its hopes and dreams. Here are the method syntaxes below:
Last updated