Skip to content
learnFRC.org
programminglesson35 min

State-Space Modeling, LQR & Kalman Filters

Formulating continuous-time state-space models, computing optimal Linear-Quadratic Regulator (LQR) gain matrices, and estimating unmeasured states with Kalman filters.

What you will learn

  • Formulate continuous-time state-space matrices (A, B, C, D) for linear and rotational mechanisms.
  • Tune state error (Q) and control effort (R) cost matrices to solve the continuous algebraic Riccati equation.
  • Construct WPILib LinearQuadraticRegulator controllers to compute optimal feedback gain vectors.
  • Implement KalmanFilter state estimators to reject sensor noise and predict unmeasured mechanism velocities.
  • Integrate plant, observer, and controller into a unified WPILib LinearSystemLoop.

Prerequisites:SysId System Characterization

Classical single-variable PID controllers treat mechanism position and velocity independently. When commanded to make large setpoint jumps, PID often saturates motor output or produces aggressive oscillations because it cannot reason about the energy of the physical system.

State-space control models all system states simultaneously in a compact matrix differential equation:

x_dot = A * x + B * u
y = C * x + D * u

Where:

  • xx: State vector (e.g., position θ\theta and angular velocity ω\omega).
  • uu: Control input vector (applied motor voltage VV).
  • yy: Measurement vector (observed sensor signals).
  • AA: System matrix (how states evolve naturally over time).
  • BB: Input matrix (how control voltage affects state derivatives).
  • CC: Output matrix (how sensors observe states).
  • DD: Feedthrough matrix (zero for physical robotic systems).

Before constructing state-space controllers:

  1. Extract your mechanism’s physical plant parameters (kVk_V and kAk_A) from SysId System Characterization.
  2. Verify that your sensor measurements use standard SI units (meters and radians).

2. Converting SysId Gains to Plant Matrices

Section titled “2. Converting SysId Gains to Plant Matrices”

WPILib provides factory methods in LinearSystemId to construct exact AA and BB matrices directly from your characterized feedforward constants:

import edu.wpi.first.math.system.plant.LinearSystemId;
import edu.wpi.first.math.system.LinearSystem;
import edu.wpi.first.math.numbers.N1;
import edu.wpi.first.math.numbers.N2;
// Construct plant model for an elevator using SysId constants:
// States: [position (m), velocity (m/s)]^T
// Input: [voltage (V)]
// Output: [position (m)]
LinearSystem<N2, N1, N1> elevatorPlant = LinearSystemId.identifyPositionSystem(
0.142, // kV in V / (m/s)
0.024 // kA in V / (m/s²)
);

3. Designing a Linear-Quadratic Regulator (LQR)

Section titled “3. Designing a Linear-Quadratic Regulator (LQR)”

An LQR (Linear-Quadratic Regulator) solves for the mathematically optimal feedback gain matrix KK by minimizing a quadratic cost function:

J = integral(x^T * Q * x + u^T * R * u) dt
  • QQ: State cost matrix. Penalizes position error and velocity overshoot.
  • RR: Effort cost matrix. Penalizes aggressive control voltage and current draw.

Bryson’s Rule provides the starting values for the diagonal elements of QQ and RR:

Q_ii = 1 / (max_acceptable_error_i)^2
R_jj = 1 / (max_allowable_control_effort_j)^2
import edu.wpi.first.math.controller.LinearQuadraticRegulator;
import edu.wpi.first.math.VecBuilder;
// Position tolerance: 0.02 meters; Velocity tolerance: 0.20 m/s
// Control effort limit: 12.0 Volts
LinearQuadraticRegulator<N2, N1, N1> lqr = new LinearQuadraticRegulator<>(
elevatorPlant,
VecBuilder.fill(0.02, 0.20), // Q diagonal elements
VecBuilder.fill(12.0), // R diagonal element
0.020 // Loop period: 20ms
);

4. State Estimation with the Kalman Filter

Section titled “4. State Estimation with the Kalman Filter”

Raw sensor signals contain quantization noise and lag. A Kalman Filter computes the optimal estimate of true mechanism position and unmeasured velocity by fusing model predictions with sensor measurements:

import edu.wpi.first.math.estimator.KalmanFilter;
// Process noise: how much model diverges (e.g. 0.05m pos, 1.0 m/s vel)
// Measurement noise: encoder resolution noise (e.g. 0.002m)
KalmanFilter<N2, N1, N1> kalmanFilter = new KalmanFilter<>(
elevatorPlant,
VecBuilder.fill(0.05, 1.0), // Model standard deviations
VecBuilder.fill(0.002), // Sensor measurement standard deviation
0.020 // Loop period
);

WPILib’s LinearSystemLoop combines the plant model, the LQR controller, the Kalman filter, and input feedforward into a unified object:

package frc.robot.subsystems;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import edu.wpi.first.math.system.LinearSystemLoop;
import edu.wpi.first.math.system.plant.LinearSystemId;
import edu.wpi.first.math.controller.LinearQuadraticRegulator;
import edu.wpi.first.math.estimator.KalmanFilter;
import edu.wpi.first.math.VecBuilder;
import edu.wpi.first.math.numbers.N1;
import edu.wpi.first.math.numbers.N2;
import com.ctre.phoenix6.hardware.TalonFX;
import com.ctre.phoenix6.controls.VoltageOut;
public class OptimalElevatorSubsystem extends SubsystemBase {
private final TalonFX m_motor = new TalonFX(12, "rio");
private final VoltageOut m_voltageReq = new VoltageOut(0.0);
private final LinearSystemLoop<N2, N1, N1> m_loop;
public OptimalElevatorSubsystem() {
var plant = LinearSystemId.identifyPositionSystem(0.142, 0.024);
var lqr = new LinearQuadraticRegulator<>(
plant,
VecBuilder.fill(0.015, 0.15),
VecBuilder.fill(12.0),
0.020
);
var observer = new KalmanFilter<>(
plant,
VecBuilder.fill(0.04, 0.80),
VecBuilder.fill(0.001),
0.020
);
m_loop = new LinearSystemLoop<>(plant, lqr, observer, 12.0, 0.020);
}
public void setGoalHeight(double targetHeightMeters) {
// Set state reference: [target position, target velocity 0.0]
m_loop.setNextR(VecBuilder.fill(targetHeightMeters, 0.0));
}
@Override
public void periodic() {
// 1. Read current encoder position in meters
double currentHeightMeters = m_motor.getPosition().getValueAsDouble() * 0.05;
// 2. Correct Kalman filter observer with sensor measurement
m_loop.correct(VecBuilder.fill(currentHeightMeters));
// 3. Step controller and observer forward
m_loop.predict(0.020);
// 4. Extract optimal voltage command and apply to motor
double optimalVoltage = m_loop.getU(0);
m_motor.setControl(m_voltageReq.withOutput(optimalVoltage));
}
}

  1. Step Response Transient:
    • Command a 1.0 meter step change in elevator height.
    • In AdvantageScope, plot measured position vs. target setpoint.
    • The response should reach 95%95\% of target in under 0.65 seconds with less than 2%2\% overshoot.
  2. Control Voltage Saturation:
    • Plot output voltage uu. The command should hit 12.0 V during initial acceleration, taper smoothly as back-EMF rises, and drop to the gravity holding voltage without violent oscillations.

You have completed Physics Simulation & Modern Control. Combine these optimal state-space controllers with Autonomous Trajectory Engineering to deliver championship-tier performance on the field.

Verified Sources & Standards

Evergreen Standard Verified: Sep 25, 2026