PID Control (Android Studio)
What is PID Control?
PID (Proportional–Integral–Derivative) adjusts motor power from error = target − measurement. It is the default way FTC teams hold position, speed, or heading when encoders or an IMU provide feedback.
How PID Works
- Proportional (P): Output scales with current error—larger miss, stronger correction.
- Integral (I): Output scales with accumulated error over time—can remove small bias that P alone leaves.
- Derivative (D): Output scales with how fast error is changing—damps overshoot and oscillation.
The PID Formula
output = kP * error + kI * integral + kD * derivative
Here error = target - actual, integral sums error × Δt, and derivative is the change in error over Δt.
Basic PID Loop in Java (Android Studio)
Position-hold example on a motor encoder:
double kP = 0.01, kI = 0.0, kD = 0.0;
double integral = 0, lastError = 0;
long lastTime = System.currentTimeMillis();
while (opModeIsActive()) {
double error = targetPosition - motor.getCurrentPosition();
long now = System.currentTimeMillis();
double dt = (now - lastTime) / 1000.0;
integral += error * dt;
double derivative = (error - lastError) / dt;
double output = kP * error + kI * integral + kD * derivative;
motor.setPower(Range.clip(output, -1, 1));
lastError = error;
lastTime = now;
if (Math.abs(error) < 10) break; // Stop if close enough
}
Tuning PID Controllers
Tune kP first until the mechanism responds quickly without violent oscillation. Add kD to calm overshoot. Add kI only if a small error remains after P and D are reasonable—and cap the integral term to limit windup. Change one gain at a time. gm0: Control loops
Sample Rate and Performance
Sample rate is how often the loop runs. Faster loops can track better but cost CPU time. Built-in motor PID in the SDK updates on the order of 20 Hz; custom loops in your OpMode can run faster if needed. gm0: PID sample rate
Troubleshooting PID
- Oscillation: Lower kP or increase kD.
- Slow response: Increase kP.
- Steady-state error: Increase kI.
- Integral windup: Limit the integral term.
Practice Exercise: PID Tuning Simulator
Practice tuning PID controllers using an interactive simulator to understand how different parameters affect system behavior.
- Open the PID Simulator at https://pknessness.github.io/pid_sim/pid.html
- Start with default values and observe the system response
- Practice tuning each parameter (kP, kI, kD) individually
- Test different scenarios using the Test Sequence button
- Record your best tuning values and explain why they work well
Caution: Using the Integral (kI) Term in Robotics
Many FTC mechanisms work well with kP and kD only. kI sums error over time; that can fix a small leftover bias, but it also builds up during saturation (integral windup) and can cause overshoot or slow drift if limits are wrong. Add kI only when you still have steady-state error after tuning P and D, use a small value, clamp the integral term, and test at low power first.