Writing the code for a PIDSubystem in Java
PIDSubsystems use feedback to control the actuator and drive it to a particular position. In this example we use an elevator with a 10-turn potentiometer connected to it to give feedback on the height. The skeleton of the PIDSubsystem is generated by the RobotBuilder and we have to fill in the rest of the code to provide the potentiometer value and drive the motor with the output of the imbedded PIDController.
Setting the PID constants
Make sure the Elevator PID subsystem has been created in the RobotBuiler. In the case of our elevator we use a propertional constant of 6.0 and 0 for the I and D terms. Once it's all set, generate Java code for the project using the Export menu or the Java toolbar menu.
Add constants for the Elevator preset positions and enable the PID controller
To make it easier to drive the elevator to preset positions, we added preset positions for the bottom, stow, and table height. Then the elevator is set to the STOW position by setting the PID setpoint and the PID controller is enabled. This will cause the elevator to move to the stowed position when the robot is enabled.
Look at the autogenerated code from RobotBuilder for returnPIDInput
The returnPIDInput() method is used to set the value of the sensor that is providing the feedback for the PID controller. In this case, the code is automatically generated and returns the potentiometer raw analog input value (a number that ranges from 0-1023). In our case we would like the PID controller to be based on the average voltage read by the analog input for the potentiometer, not the raw value.
If we just change the line:
return potentiometer.pidGet();
it will be overwritten by RobotBuilder next time we export to Java. You can tell which lines are automatically generated by looking at the "//BEGIN AUTOGENERATED CODE" and "//END AUTOGENERATED CODE" comments. Any code inbetween those markers will be overwritten next time RobotBuilder is run. You're free to change anything outside of those blocks.
Use the avarage voltage for the PID input
To get around the problem from the last step, the comment blocks can be removed. Then if the line is changed as shown, it will no longer be overwritten by RobotBuilder.
Remember, if we just wanted to add code to a method it could be added safely outside of the comment blocks.
That's all that is required to create the Elevator PIDSubsystem in Java. To operate it with commands to actually control the motion see: Operating a PIDSubsystem from a command