Step 3: Updating the Drivetrain Model¶
Now that the drivetrain model has been made, it needs to be updated periodically with the latest motor voltage commands. It is recommended to do this step in a separate
SimulationPeriodic() method inside your subsystem and only call this method in simulation.
If you are using the command-based framework, every subsystem that extends
SubsystemBase has a
SimulationPeriodic() which can be overridden. This method is automatically run only during simulation. If you are not using the command-based library, make sure you call your simulation method inside the overridden
SimulationPeriodic() of the main
Robot class. These periodic methods are also automatically called only during simulation.
There are three main steps to updating the model:
Set the input of the drivetrain model. These are the motor voltages from the two sides of the drivetrain.
Advance the model forward in time by the nominal periodic timestep (Usually 20 ms). This updates all of the drivetrain’s states (i.e. pose, encoder positions and velocities) as if 20 ms had passed.
Update simulated sensors with new positions, velocities, and angles to use in other places.
If the right side of your drivetrain is inverted, you MUST negate the right voltage in the
SetInputs() call to ensure that positive voltages correspond to forward movement.
Because the drivetrain simulator model returns positions and velocities in meters and m/s respectively, these must be converted to encoder ticks and ticks/s when calling
SetRate(). Alternatively, you can configure
SetDistancePerPulse on the encoders to have the
Encoder object take care of this automatically – this is the approach that is taken in the example above.
Now that the simulated encoder positions, velocities, and gyroscope angles have been set, you can call
m_leftEncoder.GetDistance(), etc. in your robot code as normal and it will behave exactly like it would on a real robot. This involves performing odometry calculations, running velocity PID feedback loops for trajectory tracking, etc.