calculate() function simply outputs a percent output value to apply to your motor using the motor controller’s
set() function. The example code you posted is exactly what you need to get the motor to reach the setpoint using PID. What it does is set your motor to the percent output value calculated by the PID controller. You need to be constantly updating the
motor.set(pid.calculate(encoder.getDistance(), setpoint)); code however, since it will need to be constantly applying the correct percent output as calculated by the PIDController to reach the setpoint. So run this code in a loop updated at a certain frequency, called the
period of the PIDController. By default, the
period you want to run the loop at is every 0.02 seconds, although it can be changed in the PIDController’s constructor.
In order to “stop” at the setpoint like you mentioned, the PIDController class has functions to detect when the motor has reached the setpoint. You first want to call
pid.setTolerance(positionTolerance, velocityTolerance) to set the tolerances of the PIDController. Tolerances are how far away from the setpoint you are satisfied with to stop the motor.
After the tolerances are set, you can check for the boolean
pid.atSetpoint(), which will return true if your motor’s position is within the tolerance you set. After that boolean returns true, you can simply set the motor percent output to 0, therefore stopping the motor when you have reached a setpoint.