We have a Through Bore Encoder that measures the rotation of the wheels and we have it plugged into the data port on top of the SparkMax motor controller with an absolute adaptor plugged into it. We do have the mode in the motor controller set to Default as the alternative encoder.
The encoder keeps trying to go up to the desired position but after around 55 degrees it returns to 0 and never reaches the desired position, therefore making it spin forever.
private final SparkAbsoluteEncoder absoluteEncoder;
absoluteEncoder = turningMotor.getAbsoluteEncoder(SparkAbsoluteEncoder.Type.kDutyCycle);
driveEncoder.setVelocityConversionFactor(ModuleConstants.DRIVING_ENCODER_VELOCITY_FACTOR);
turningEncoder.setPositionConversionFactor(ModuleConstants.TURNING_ENCODER_POSITION_FACTOR);
turningEncoder.setVelocityConversionFactor(ModuleConstants.DRIVING_ENCODER_VELOCITY_FACTOR);
public void setDesiredState(SwerveModuleState desiredState) {
// Optimize the reference state to avoid spinning further than 90 degrees
desiredState.angle = desiredState.angle.plus(new Rotation2d(absoluteEnocderOffet));
SwerveModuleState state =
SwerveModuleState.optimize(desiredState, new Rotation2d(getAbsoluteEncoderRad()));
System.out.println(state.angle);
// Calculate the drive output from the drive PID controller.
final double driveOutput =
drivePIDController.calculate(driveEncoder.getVelocity(), state.speedMetersPerSecond * 2);
// Calculate the turning motor output from the turning PID controller.
final double turnOutput =
turningPIDController.calculate(getAbsoluteEncoderRad(), state.angle.getRadians());
// Calculate the turning motor output from the turning PID controller
driveMotor.set(driveOutput);
turningMotor.set(turnOutput / 5);
}
public double getAbsoluteEncoderRad() {
return Math.toDegrees(absoluteEncoder.getPosition());
}
Constants:
public static final double DRIVING_ENCODER_VELOCITY_FACTOR = ((WHEEL_DIAMETER_METERS * Math.PI) / DRIVING_MOTOR_REDUCTION) / 60.0;
public static final double TURNING_ENCODER_POSITION_FACTOR = (Math.PI * 2);