Once a Subsystem encapsulates its hardware, you need commands to trigger actions: moving an arm to a scoring preset, running intake rollers until a piece is detected, or holding an elevator at a specific height.
Modern WPILib emphasizes Command Factory Methods declared directly on the Subsystem class, supplemented by dedicated Command classes for complex multi-step routines.
1. Subsystem Command Factories
Section titled “1. Subsystem Command Factories”Rather than creating a new .java file for every simple action, declare factory methods directly inside your Subsystem. This keeps related logic co-located and ensures requirements are attached automatically:
public class ArmSubsystem extends SubsystemBase { // ... hardware handles and configuration ...
/** Factory: Moves arm to target angle and finishes when within tolerance. */ public Command moveToAngleCommand(Angle target) { return this.run(() -> setTargetAngle(target)) .until(() -> isAtAngle(target, Degrees.of(2.0))) .withTimeout(Seconds.of(2.5)) .withName("ArmMoveToAngle"); }
/** Factory: Holds the current angle indefinitely (ideal as default command). */ public Command holdPositionCommand() { return this.run(() -> setTargetAngle(getAngle())) .withName("ArmHoldPosition"); }
/** Helper: Checks if arm is within tolerance of target. */ public boolean isAtAngle(Angle target, Angle tolerance) { return Math.abs(getAngle().in(Degrees) - target.in(Degrees)) < tolerance.in(Degrees); }}Key Advantages of Factory Methods:
Section titled “Key Advantages of Factory Methods:”- Implicit Requirements: Calling
this.run(...)automatically adds the subsystem to the command’s requirements list. - Method Chaining: Fluent decorators (
.until(),.withTimeout(),.andThen()) can be chained cleanly without boilerplate classes. - Encapsulation: Internal calibration methods remain private to the subsystem.
2. Three Production Command Patterns
Section titled “2. Three Production Command Patterns”Pattern A: Setpoint Move with Safety Timeout
Section titled “Pattern A: Setpoint Move with Safety Timeout”When moving a mechanism to a target position in autonomous, physical obstacles or low battery voltage can prevent the motor from reaching the exact setpoint. Without a timeout, your autonomous routine halts forever:
public Command scorePresetCommand() { return moveToAngleCommand(Degrees.of(75.0)) .withTimeout(Seconds.of(1.5)); // Safety: proceed after 1.5s even if slightly short}Pattern B: Sensor-Based Action with Current Spike Guard
Section titled “Pattern B: Sensor-Based Action with Current Spike Guard”An intake roller should pull game pieces in until a beam-break detects the object, or until stator current spikes indicating a mechanical jam:
public Command intakeUntilCapturedCommand() { return this.run(() -> m_rollerMotor.setVoltage(8.0)) .until(() -> isBeamBreakTripped() || isCurrentSpikeDetected()) .finallyDo((interrupted) -> m_rollerMotor.setVoltage(0.0)) .withTimeout(Seconds.of(3.0));}Pattern C: Manual Jog Command
Section titled “Pattern C: Manual Jog Command”For driver test adjustments, a command can read joystick inputs directly:
public Command manualJogCommand(DoubleSupplier jogInput) { return this.run(() -> { double input = jogInput.getAsDouble(); if (Math.abs(input) > 0.1) { // 10% deadband m_motor.setVoltage(input * 3.0); // max 3V jog } else { setTargetAngle(getAngle()); // hold position when stick is released } });}3. Dedicated Command Classes
Section titled “3. Dedicated Command Classes”Use a standalone Command class (extending Command) when:
- The behavior involves complex state transitions or external network calls.
- The command coordinates multiple subsystems simultaneously (e.g. driving swerve while elevating an arm).
public class ScoreSequenceCommand extends Command { private final ArmSubsystem m_arm; private final ElevatorSubsystem m_elevator;
public ScoreSequenceCommand(ArmSubsystem arm, ElevatorSubsystem elevator) { m_arm = arm; m_elevator = elevator; // Requires both subsystems addRequirements(m_arm, m_elevator); } // ... lifecycle methods ...}Every mechanism command in an autonomous sequence should include .withTimeout(). If a game piece jams the intake, a 2.0-second timeout ensures the robot still proceeds to shoot remaining game pieces rather than stalling for the remainder of the 15-second autonomous period.
Common Failure Modes
Section titled “Common Failure Modes”1. Setpoint Tolerance Too Strict
Section titled “1. Setpoint Tolerance Too Strict”- Symptom: Command runs until the safety timeout on every execution, never finishing via
until(). - Cause: Tolerance was set to
0.001 degrees, which mechanical backlash and sensor noise cannot satisfy. - Fix: Set practical tolerances (e.g.
±1.5 degreesfor arms,±0.5 inchesfor elevators).
2. Forgetting finallyDo()
Section titled “2. Forgetting finallyDo()”- Symptom: When a command is interrupted by releasing a button, the motor keeps spinning.
- Cause: Voltage was commanded during
execute(), but no cleanup was registered for cancellation. - Fix: Attach
.finallyDo((interrupted) -> stop())to reset motor voltage to zero.
Check Your Work
Section titled “Check Your Work”- Call your factory command in
RobotContainer:m_operator.a().onTrue(m_arm.moveToAngleCommand(Degrees.of(45.0))); - In simulation, press ‘A’. Verify the command starts, drives angle toward 45°, reports finished when within tolerance, and returns control to the default command.
Verified Sources & Standards
- WPILib Command Creation & Compositiondocs.wpilib.orgWPILib Standard