Skip to content
learnFRC.org
programminglesson30 min

Writing Mechanism Commands

Command factory methods on Subsystems vs standalone Command classes, setpoint moves with timeouts, and sensor-based termination.

What you will learn

  • Write fluent subsystem command factories using runOnce(), run(), and startEnd().
  • Build standalone Command classes with explicit lifecycle methods.
  • Implement sensor-based termination and safety timeouts with withTimeout().

Prerequisites:Building Mechanism Subsystems

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.


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);
}
}
  1. Implicit Requirements: Calling this.run(...) automatically adds the subsystem to the command’s requirements list.
  2. Method Chaining: Fluent decorators (.until(), .withTimeout(), .andThen()) can be chained cleanly without boilerplate classes.
  3. Encapsulation: Internal calibration methods remain private to the subsystem.

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));
}

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
}
});
}

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 ...
}
Always Use withTimeout in Auto

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.


  • 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 degrees for arms, ±0.5 inches for elevators).
  • 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.

  1. Call your factory command in RobotContainer:
    m_operator.a().onTrue(m_arm.moveToAngleCommand(Degrees.of(45.0)));
  2. 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

Evergreen Standard Verified: Sep 25, 2026