Mechanism Simulation
No mechanism yet? A physics model can stand in for it. Your code runs unchanged, and a picture shows where the mechanism went.
- Workshops 3 and 4 done, through Coroutines.
- The
mech-simbranch checked out and building. - An Xbox-style controller plugged into the laptop.
What mechanism are you working on?
The lesson below is written for the one you pick. Switch back any time to read it for the other.
Simulate, not Hardware Sim
Hardware Simulation used Hardware Sim Robot Code, where the motors were real. This lesson uses Simulate Robot Code, where the motors are simulated too. A simulated Talon accepts every request and runs its closed loop, but nothing turns its rotor. Something has to play the part of the armflywheel, and that is the sim class.
The branch adds four files. ArmFlywheelSim.java sits in mechanisms/ beside the class it models, and it is the one to read and change. The two in utils/ you copy as they are: SimUtil handles the CTRE setup and MechanismViews draws the picture. Both are printed whole under Your own mechanism.
The sim class
The top of the class is the real mechanism, written down. WPILib provides the physics model, and its constructor takes every number.
// The real arm, from its bill of materials. Change these and the simulated arm changes with them. static final double GEARING = 28.125; // 8:60 then 16:60: motor turns per arm turn static final double LENGTH_METERS = Arm.LENGTH.in(Meters); // pivot to tip static final double MASS_KG = 0.3; // WPILib's model of an arm swinging on one joint, under gravity. private final SingleJointedArmSim physics = new SingleJointedArmSim( DCMotor.getKrakenX44(1), // the motor driving it GEARING, SingleJointedArmSim.estimateMOI(LENGTH_METERS, MASS_KG), // how hard it is to swing LENGTH_METERS, Double.NEGATIVE_INFINITY, // no hard stops: it can swing all the way round Double.POSITIVE_INFINITY, true, // gravity Units.rotationsToRadians(0.75)); // starts hanging straight down // The real flywheel. The motor's speed is the wheel speed your code commands, so the gearing here // is 1, matching the config. private static final double GEARING = 1.0; private static final double MOMENT_OF_INERTIA = 0.002; // kg·m², how hard it is to spin up private static final DCMotor MOTOR = DCMotor.getKrakenX44(1); // WPILib's model of a spinning wheel. (Written out in full because it shares this class's name.) private final org.wpilib.simulation.FlywheelSim physics = new org.wpilib.simulation.FlywheelSim( Models.flywheelFromPhysicalConstants(MOTOR, MOMENT_OF_INERTIA, GEARING), MOTOR);Every loop, update() takes three steps. It reads the voltage the simulated motor is applying and hands it to the model. The model moves the armflywheel forward 20 ms. The result goes back into the simulated devices, so your code reads it the way it would read a real sensor.
// 1. Voltage in: what the motor is applying, from the battery we give it. motorSim.Orientation = SimUtil.orientationOf(motor); motorSim.setSupplyVoltage(RobotController.getBatteryVoltage()); encoderSim.setSupplyVoltage(RobotController.getBatteryVoltage()); physics.setInputVoltage(motorSim.getMotorVoltage()); // 2. Physics: how the arm moves in one 20 ms loop. physics.update(0.020); // 3. Motion out: the CANcoder sits on the arm shaft, so it reads the arm itself. // The motor's rotor spins GEARING times faster than the arm. double armRotations = Units.radiansToRotations(physics.getAngle()); double armRotationsPerSecond = Units.radiansToRotations(physics.getVelocity()); encoderSim.setRawPosition(armRotations); encoderSim.setVelocity(armRotationsPerSecond); motorSim.setRawRotorPosition(armRotations * GEARING); motorSim.setRotorVelocity(armRotationsPerSecond * GEARING);Before its first step, the arm copies the CANcoder's direction and magnet offset onto the simulated CANcoder, through SimUtil.matchCANcoderConfig. Without that the simulated CANcoder ignores the offset, and the angle your code reads is not the angle the model holds.
// 1. Voltage in: what the motor is applying, from the battery we give it. motorSim.Orientation = SimUtil.orientationOf(motor); motorSim.setSupplyVoltage(RobotController.getBatteryVoltage()); physics.setInputVoltage(motorSim.getMotorVoltage()); // 2. Physics: how the wheel speeds up or slows down in one 20 ms loop. physics.update(0.020); // 3. Motion out: the rotor spins GEARING times faster than the wheel. double wheelRotationsPerSecond = Units.radiansToRotations(physics.getAngularVelocity()); wheelRotations += wheelRotationsPerSecond * 0.020; motorSim.setRawRotorPosition(wheelRotations * GEARING); motorSim.setRotorVelocity(wheelRotationsPerSecond * GEARING);Hook it into the mechanism
Two calls go at the end of the Arm.javaFlywheel.java constructor, after the config is applied. The picture is drawn from what the motor reports, so it runs on a real robot too. The sim is built only under Simulate Robot Code, which is what Phoenix's Utils.isSimulation() reports. A deployed robot and Hardware Sim both skip it.
motor.getConfigurator().apply(talonFXCfg); // A picture of the arm, drawn from what the motor reports. Runs everywhere. MechanismViews.arm("ArmView", motor, LENGTH); // Simulate Robot Code only: there is no real arm, so physics plays its part. if (Utils.isSimulation()) { new ArmSim(motor, encoder); }LENGTH is a new field on Arm, Inches.of(9), because the picture and the physics both need it.
motor.getConfigurator().apply(talonFXCfg); // A speed gauge, drawn from what the motor reports. A full bar is 100 rotations per second. MechanismViews.flywheel("FlywheelView", motor, 100); // Simulate Robot Code only: there is no real flywheel, so physics plays its part. if (Utils.isSimulation()) { new FlywheelSim(motor); }Nothing goes in Robot.java. The sim registers its own loop with the scheduler, the same way the picture does. That registration lasts as long as whatever made it, so build the mechanism as a field on Robot. One built inside an OpMode would stop simulating when that OpMode ended.
Run it
The branch ships every gain at 0.0, so the simulated armflywheel holds still at first. Give it gains of your own before you run it.
- In the config in Arm.javaFlywheel.java, enter your own starting
kG,kP, cruise velocity and acceleration. Motion Magic will not move with a cruise velocity of 0.kV,kPand acceleration. The velocity profile ramps at that acceleration and has no cruise velocity. - Open the … menu at the end of the editor toolbar and choose Simulate Robot Code. Keep Sim GUI ticked.
- Drop the controller on Joystick[0], pick Teleoperated and your OpMode, and enable, as in Hardware Simulation.
- From the NetworkTables menu, open Telemetry, then ArmViewFlywheelView. You should see: an orange arm hanging straight down.an empty gauge.
- Hold the buttons you bound. You should see: the picture follow, with a thin grey line marking the target while the closed loop is chasing it.
Tune the way PID Tuning in Tuner X does, in the same order, but change the number in code and restart the simulation between tries. These gains tune a model, not your mechanism, so expect to tune again once it is built.
Your own mechanism
Copy the four files into your project and change the numbers at the top of the sim class to match your design: the gearing, the length and mass of the arm,the wheel's moment of inertia, and the motor in DCMotor. Most of them come from your CAD.
The two utils/ files go in unchanged. Each is folded here. Copy it from the header, or open it to read.
SimUtil.java77 lines
// Copyright (c) FIRST and other WPILib contributors.// Open Source Software; you can modify and/or share it under the terms of// the WPILib BSD license file in the root directory of this project. package first.robot.utils; import com.ctre.phoenix6.configs.MagnetSensorConfigs;import com.ctre.phoenix6.hardware.CANcoder;import com.ctre.phoenix6.hardware.TalonFX;import com.ctre.phoenix6.signals.AppliedRotorPolarityValue;import com.ctre.phoenix6.signals.SensorDirectionValue;import com.ctre.phoenix6.sim.ChassisReference;import java.util.HashMap;import java.util.Map;import org.wpilib.command3.Scheduler; /** * The CTRE plumbing a mechanism simulation needs, so the {@code ...Sim} classes can stay about the * physics. */public final class SimUtil { private SimUtil() {} /** * Which way the motor is mounted, for its {@code SimState.Orientation}. CTRE's own swerve * simulation uses Clockwise_Positive when the motor is inverted. This reads the direction the * Talon reports it is applying, which follows the Inverted config. */ public static ChassisReference orientationOf(TalonFX motor) { return motor.getAppliedRotorPolarity().getValue() == AppliedRotorPolarityValue.PositiveIsClockwise ? ChassisReference.Clockwise_Positive : ChassisReference.CounterClockwise_Positive; } /** * Copies a CANcoder's sensor direction and magnet offset onto its {@code SimState}, the way * CTRE's own swerve simulation does, so the simulated CANcoder reports the true angle. Reading a * config can time out while the simulator is still starting, so call this every loop until it * returns true. */ public static boolean matchCANcoderConfig(CANcoder encoder) { var magnet = new MagnetSensorConfigs(); if (!encoder.getConfigurator().refresh(magnet, 0.05).isOK()) { return false; } var encoderSim = encoder.getSimState(); encoderSim.Orientation = magnet.SensorDirection == SensorDirectionValue.Clockwise_Positive ? ChassisReference.Clockwise_Positive : ChassisReference.CounterClockwise_Positive; encoderSim.SensorOffset = magnet.MagnetOffset; return true; } // The newest simulation for each motor. Building a mechanism twice (every JUnit test does) // retires the old simulation instead of running two against the same device. private static final Map<String, Runnable> newest = new HashMap<>(); /** * Runs {@code step} once every robot loop, for as long as it is the newest simulation of this * motor. Call it from a constructor that runs before any OpMode: started inside an OpMode or a * command, the scheduler stops it when that OpMode or command ends. */ public static void everyLoop(TalonFX motor, Runnable step) { String device = motor.getNetwork().getName() + ":" + motor.getDeviceID(); newest.put(device, step); Scheduler.getDefault() .sideload( coroutine -> { while (newest.get(device) == step) { step.run(); coroutine.yield(); } }); }}MechanismViews.java118 lines
// Copyright (c) FIRST and other WPILib contributors.// Open Source Software; you can modify and/or share it under the terms of// the WPILib BSD license file in the root directory of this project. package first.robot.utils; import static org.wpilib.units.Units.Meters; import com.ctre.phoenix6.BaseStatusSignal;import com.ctre.phoenix6.hardware.TalonFX;import com.ctre.phoenix6.signals.ControlModeValue;import org.wpilib.command3.Scheduler;import org.wpilib.smartdashboard.Mechanism2d;import org.wpilib.smartdashboard.MechanismLigament2d;import org.wpilib.smartdashboard.MechanismRoot2d;import org.wpilib.telemetry.Telemetry;import org.wpilib.units.measure.Distance;import org.wpilib.util.Color;import org.wpilib.util.Color8Bit; /** * Mechanism2d pictures of a mechanism, drawn from what its motor reports. They run everywhere: on a * SystemCore, in Hardware Sim and in Simulate Robot Code, so the picture always shows the real (or * simulated) mechanism and the target its closed loop is chasing. * * <p>Open them in the Sim GUI or AdvantageScope under the name you give. */public final class MechanismViews { private MechanismViews() {} /** * An arm: a thick orange line where the motor says the arm is, and a thin grey line at its * position target while a position loop (such as Motion Magic) is running. Angles are the motor's * own: 0 points right, 0.25 rotations straight up. */ public static void arm(String name, TalonFX motor, Distance length) { double lengthMeters = length.in(Meters); double size = lengthMeters * 2.4; var view = new Mechanism2d(size, size); MechanismRoot2d pivot = view.getRoot("pivot", size / 2, size / 2); // The target goes first so the arm draws over it. MechanismLigament2d target = pivot.append(new MechanismLigament2d("target", 0, 0, 3, new Color8Bit(Color.GRAY))); MechanismLigament2d arm = pivot.append( new MechanismLigament2d("arm", lengthMeters, 0, 8, new Color8Bit(Color.ORANGE))); // Grabbed once and refreshed together every loop, quietly: a missing motor just stops the // picture instead of printing an error 50 times a second. var position = motor.getPosition(false); var mode = motor.getControlMode(false); var reference = motor.getClosedLoopReference(false); Scheduler.getDefault() .addPeriodic( () -> { if (!BaseStatusSignal.refreshAll(position, mode, reference).isOK()) { return; } arm.setAngle(position.getValueAsDouble() * 360); if (isPositionControl(mode.getValue())) { target.setLength(lengthMeters); target.setAngle(reference.getValueAsDouble() * 360); } else { target.setLength(0); } Telemetry.log(name, view); }); } /** * A flywheel, as a speed gauge: a wheel at 75 rotations per second can't be drawn turning when * the picture updates 50 times a second. A thick orange bar for how fast it is spinning, and a * thin grey bar for its target speed while a velocity loop is running. A full bar is {@code * fullScaleRps}. */ public static void flywheel(String name, TalonFX motor, double fullScaleRps) { var view = new Mechanism2d(1.2, 0.5); MechanismRoot2d targetRoot = view.getRoot("target", 0.1, 0.3); MechanismRoot2d speedRoot = view.getRoot("speed", 0.1, 0.2); MechanismLigament2d target = targetRoot.append(new MechanismLigament2d("target", 0, 0, 3, new Color8Bit(Color.GRAY))); MechanismLigament2d speed = speedRoot.append(new MechanismLigament2d("speed", 0, 0, 12, new Color8Bit(Color.ORANGE))); // Grabbed once and refreshed together every loop, quietly, as in arm(). var velocity = motor.getVelocity(false); var mode = motor.getControlMode(false); var reference = motor.getClosedLoopReference(false); Scheduler.getDefault() .addPeriodic( () -> { if (!BaseStatusSignal.refreshAll(velocity, mode, reference).isOK()) { return; } speed.setLength(gauge(velocity.getValueAsDouble(), fullScaleRps)); if (mode.getValue().toString().contains("Velocity")) { target.setLength(gauge(reference.getValueAsDouble(), fullScaleRps)); } else { target.setLength(0); } Telemetry.log(name, view); }); } /** True while the motor runs a position loop, so its closed-loop reference is an angle. */ private static boolean isPositionControl(ControlModeValue mode) { String name = mode.toString(); return name.contains("Position") || (name.contains("MotionMagic") && !name.contains("Velocity")); } /** A speed as a bar length, 0 to 1 m. Reverse is drawn the same as forward. */ private static double gauge(double rps, double fullScaleRps) { return Math.min(Math.abs(rps) / fullScaleRps, 1.0); }}Change the motor in one more place. A simulated Talon models its own motor for current limiting, and it assumes a Kraken X60 unless told. The bench runs a Kraken X44, so the constructor says so:
motorSim.setMotorType(TalonFXSimState.MotorType.KrakenX44);Left at the X60, the simulated bench arm ran away from its target with the output pinned near its limit.
Check your work
You should see
- The arm swing to vertical while you hold the left trigger, and its orange line settle on the grey target line.
- The orange bar climb to the grey target bar while you hold A, and drop back when you let go.
Check yourself
Under Simulate Robot Code, the arm's sim class is never built. What happens when you hold a button?
Why is the sim built inside if (Utils.isSimulation()) rather than every time?
You tune your arm in simulation, then build the real arm. What should you expect?