Setting motor postion with encoder

Hello There!
My team and I are looking to program predetermined rotations for one of our motors. We already have an encoder mounted but need direction for the actually code used.

Thanks! |
Our current code V

private Encoder m_Encoder = new Encoder(0, 1, true, Encoder.EncodingType.k4X);
double EncoderValue = 0.0;

public void teleopPeriodic() {

if (m_driveStick.getRawButton(11)) {
	if (m_Encoder.get() > 0) {
		EncoderValue = m_Encoder.get();
	else if (m_Encoder.get() > 1) {



It’s hard to tell you exactly what method will work best, but there are a few methods. The way we handled motion last year was like this.

void setPosition(double targetPos) {
double currentPos = m_Encoder.get();
double speed = targetPos - currentPos;
speed /= RATE; // RATE is some predefined constant

This method may work for you, although there may be some special logic you need to write for yourself such as deadbands and going up vs going down.

Another method is PID controllers which have been implemented by WPI but may require a significant amount of tuning. You can learn more about them here:

I highly suggest looking into PID. Or if you are using TalonSRXs, I would also look into its documentation. There is a lot of good stuff for positional control.

What you have is a very simple control method: if it is over stop, under keep going. This is fine but there are much more precise methods.

PID (proportional, integral, derivative) is a more elegant more more advanced control method. WPI has a PIDController class. PID does require lots of tuning/trial and error.

PIDController elevatorPID = new PIDController(double P, double I, double D, m_Encoder, new PIDOutput());
elevatorPID.setOutputRange(double minSpeed, double maxSpeed);
elevatorPID.setAbsoluteTolerance(double allowedError);

*PIDOutput is an interface so you must create a class that implements it

Use the following methods in your control loop

.setSetpoint(double setpoint) : the encoder value the PID is approaching
.get() : returns the speed calculated by PID
.onTarget() : returns if the encoder is within the margin of error of the setpoint

Depending on the motor controllers you are using, there might be built in encoding and PID capabilities which have their own libraries

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.