# Physics Simulation with WPILib¶

Because state-space notation allows us to compactly represent the of , we can leverage it to provide a backend for simulating physical systems on robots. The goal of these simulators is to simulate the motion of robot mechanisms without modifying existing non-simulation user code. The basic flow of such simulators is as follows:

• In normal user code:

• PID or similar control algorithms generate voltage commands from encoder (or other sensor) readings

• Motor outputs are set

• In simulation periodic code:

• The simulation’s is updated using , usually voltages from motors set from a PID loop

• Simulated encoder (or other sensor) readings are set for user code to use in the next timestep

## WPILib’s Simulation Classes¶

The following physics simulation classes are available in WPILib:

• LinearSystemSim, for modeling systems with linear dynamics

• FlywheelSim

• DifferentialDrivetrainSim

• ElevatorSim, which models gravity

• SingleJointedArmSim, which models gravity

• BatterySim, which simply estimates battery voltage sag based on drawn currents

All simulation classes (with the exception of the differential drive simulator) inherit from the LinearSystemSim class. By default, the dynamics are the linear system dynamics $$\mathbf{x}_{k+1} = \mathbf{A}\mathbf{x}_k + \mathbf{B}\mathbf{u}_k$$. Subclasses override the UpdateX(x, u, dt) method to provide custom, nonlinear dynamics, such as modeling gravity.

## Usage in User Code¶

The following is available from the WPILib elevatorsimulation example project.

In addition to standard objects such as motors and encoders, we instantiate our elevator simulator using known constants such as carriage mass and gearing reduction. We also instantiate an EncoderSim, which sets the distance and rate read by our our Encoder.

In the following example, we simulate an elevator given the mass of the moving carriage (in kilograms), the radius of the drum driving the elevator (in meters), the gearing reduction between motor and drum as output over input (so usually greater than one), the minimum and maximum height of the elevator (in meters), and some random noise to add to our position estimate.

Note

The elevator and arm simulators will prevent the simulated position from exceeding given minimum or maximum heights or angles. If you wish to simulate a mechanism with infinite rotation or motion, LinearSystemSim may be a better option.

 36 37 38 39 40 41 42 43  private final ElevatorSim m_elevatorSim = new ElevatorSim(m_elevatorGearbox, kElevatorGearing, kCarriageMass, kElevatorDrumRadius, kMinElevatorHeight, kMaxElevatorHeight, VecBuilder.fill(0.01)); private final EncoderSim m_encoderSim = new EncoderSim(m_encoder); 

Next, teleopPeriodic/TeleopPeriodic (Java/C++) uses a simple PID control loop to drive our elevator to a setpoint 30 inches off the ground.

 36 37 38 39 40 41 42 43 44 45 46  @Override public void teleopPeriodic() { if (m_joystick.getTrigger()) { // Here, we run PID control like normal, with a constant setpoint of 30in. double pidOutput = m_controller.calculate(m_encoder.getDistance(), Units.inchesToMeters(30)); m_motor.setVoltage(pidOutput); } else { // Otherwise, we disable the motor. m_motor.set(0.0); } } 

Next, simulationPeriodic/SimulationPeriodic (Java/C++) uses the voltage applied to the motor to update the simulated position of the elevator. We use SimulationPeriodic because it runs periodically only for simulated robots. This means that our simulation code will not be run on a real robot.

Finally, the simulated encoder’s distance reading is set using the simulated elevator’s position, and the robot’s battery voltage is set using the estimated current drawn by the elevator.

 68 69 70 71 72 73 74 75 76 77 78 79 80 81  @Override public void simulationPeriodic() { // In this method, we update our simulation of what our elevator is doing // First, we set our "inputs" (voltages) m_elevatorSim.setInput(m_motor.get() * RobotController.getBatteryVoltage()); // Next, we update it. The standard loop time is 20ms. m_elevatorSim.update(0.020); // Finally, we set our simulated encoder's readings and simulated battery voltage m_encoderSim.setDistance(m_elevatorSim.getPositionMeters()); // SimBattery estimates loaded battery voltages RoboRioSim.setVInVoltage(BatterySim.calculateDefaultBatteryLoadedVoltage(m_elevatorSim.getCurrentDrawAmps())); }