Writing separate code for simulation and physical hardware introduces bugs and divergence. The gold standard in FRC software engineering is zero code bifurcation: the exact same subsystem classes, commands, and autonomous routines execute identically on physical roboRIO hardware and desktop simulation.
This is achieved by implementing the virtual loopback inside simulationPeriodic().
1. What to Learn First
Section titled “1. What to Learn First”Before wiring simulation hardware:
- Ensure your subsystem is cleanly encapsulated with private motor handles and public command factories as taught in Building Mechanism Subsystems.
- Confirm your physics simulation parameters from Mechanism Physics Models.
2. The Simulation Loopback Pattern
Section titled “2. The Simulation Loopback Pattern”Every 20 milliseconds, the WPILib desktop simulator executes two periodic passes:
1. Subsystem periodic() (Commands calculate motor output voltage) │ ▼2. Subsystem simulationPeriodic() ├─ a. Read motor output voltage from TalonFXSimState / SparkSim ├─ b. Pass voltage to physics model (e.g., m_armSim.setInputVoltage()) ├─ c. Advance physics simulation by 20ms (m_armSim.update(0.020)) └─ d. Write simulated position & velocity back to motor SimStateWhen your subsystem reads encoder position on the next cycle, it reads the physics-generated state seamlessly.
3. Implementing simulationPeriodic() in an Arm Subsystem
Section titled “3. Implementing simulationPeriodic() in an Arm Subsystem”Below is the complete simulation loopback for a Talon FX powered arm using Phoenix 6 and WPILib:
package frc.robot.subsystems;
import edu.wpi.first.wpilibj2.command.SubsystemBase;import edu.wpi.first.wpilibj.simulation.SingleJointedArmSim;import edu.wpi.first.math.system.plant.DCMotor;import edu.wpi.first.math.util.Units;import com.ctre.phoenix6.hardware.TalonFX;import com.ctre.phoenix6.sim.TalonFXSimState;
public class ArmSubsystemWithSim extends SubsystemBase { private final TalonFX m_motor = new TalonFX(15, "rio"); private final TalonFXSimState m_motorSim = m_motor.getSimState();
private static final double GEAR_RATIO = 65.0;
// Physics simulator instance private final SingleJointedArmSim m_armSim = new SingleJointedArmSim( DCMotor.getKrakenX60(1), GEAR_RATIO, 0.42, // Moment of inertia in kg*m² 0.72, // Arm length in meters Units.degreesToRadians(-20.0), Units.degreesToRadians(105.0), true, // Enable gravity Units.degreesToRadians(0.0) );
@Override public void simulationPeriodic() { // 1. Extract voltage commanded by onboard closed-loop or teleop commands double motorVoltage = m_motorSim.getMotorVoltage();
// 2. Pass voltage into the physics simulation m_armSim.setInputVoltage(motorVoltage);
// 3. Step physics simulation forward by 20ms m_armSim.update(0.020);
// 4. Convert mechanism radians to motor rotor rotations double mechanismRotations = m_armSim.getAngleRads() / (2.0 * Math.PI); double rotorRotations = mechanismRotations * GEAR_RATIO; double rotorVelocityRPS = (m_armSim.getVelocityRadPerSec() / (2.0 * Math.PI)) * GEAR_RATIO;
// 5. Update simulated sensor state m_motorSim.setRawRotorPosition(rotorRotations); m_motorSim.setRotorVelocity(rotorVelocityRPS); m_motorSim.setSupplyVoltage(12.0 - m_armSim.getCurrentDrawAmps() * 0.025); // Model battery internal resistance }}4. Animating Mechanisms with Mechanism2d
Section titled “4. Animating Mechanisms with Mechanism2d”WPILib provides Mechanism2d to visualize mechanism links and elevators in Glass, SimGUI, and AdvantageScope:
import edu.wpi.first.wpilibj.smartdashboard.Mechanism2d;import edu.wpi.first.wpilibj.smartdashboard.MechanismRoot2d;import edu.wpi.first.wpilibj.smartdashboard.MechanismLigament2d;import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;import edu.wpi.first.wpilibj.util.Color;import edu.wpi.first.wpilibj.util.Color8Bit;
public class ArmVisualizer { private final Mechanism2d m_canvas = new Mechanism2d(1.5, 1.5); private final MechanismRoot2d m_pivot = m_canvas.getRoot("ArmPivot", 0.75, 0.4); private final MechanismLigament2d m_armLigament = m_pivot.append( new MechanismLigament2d("Arm", 0.72, 0.0, 6.0, new Color8Bit(Color.kYellow)) );
public ArmVisualizer() { SmartDashboard.putData("Mechanism2d/ArmView", m_canvas); }
public void update(double angleDegrees) { m_armLigament.setAngle(angleDegrees); }}How Success is Checked
Section titled “How Success is Checked”- SimGUI Execution:
- In VS Code, press F5 to launch simulation.
- In SimGUI, open NetworkTables -> SmartDashboard -> Mechanism2d -> ArmView.
- Trigger the arm preset button on your plugged-in USB gamepad.
- The arm ligament on screen should swing smoothly to the target position, settling without oscillation.
- Current and Voltage Tracking in AdvantageScope:
- Open AdvantageScope and connect to localhost.
- Verify that simulated battery voltage dips realistically during rapid arm movements and recovers when stationary.
Where to Go Next
Section titled “Where to Go Next”Now that mechanism simulation is running, proceed to Module 2: SysId Characterization & State-Space Control to mathematically characterize hardware and apply optimal control theory.
Verified Sources & Standards
- WPILib Mechanism2d Documentationdocs.wpilib.orgWPILib Standard
- CTRE Phoenix 6 Simulation Guidev6.docs.ctr-electronics.comHardware Vendor