In WPILib, robot behavior is orchestrated by the CommandScheduler. Instead of writing monolithic loops with complex conditional branches, behaviors are encapsulated into discrete Commands.
The scheduler manages command lifecycle states and subsystem requirements to prevent conflicting commands from controlling the same actuator simultaneously.
1. The 20ms CommandScheduler Loop
Section titled “1. The 20ms CommandScheduler Loop”Every 20 milliseconds (50 times per second), the roboRIO executes one iteration of the scheduler loop:
1. Poll Triggers & Buttons -> 2. Run Subsystem periodic() -> 3. Run Command execute() -> 4. Check isFinished()- Poll Triggers: Evaluates controller buttons, joystick thresholds, and sensor states.
- Subsystem
periodic(): Runs sensor updates, logging, and telemetry on every subsystem regardless of whether a command is active. - Command
execute(): Runs active commands that have been scheduled. - Evaluate
isFinished(): If a command reportstrue, the scheduler removes it and calls itsend(false)method.
2. The Four Lifecycle Methods
Section titled “2. The Four Lifecycle Methods”Every Command class defines four lifecycle methods:
package frc.robot.commands;
import edu.wpi.first.wpilibj2.command.Command;import frc.robot.subsystems.IntakeSubsystem;import static edu.wpi.first.units.Units.*;
public class RunIntakeUntilDetectedCommand extends Command { private final IntakeSubsystem m_intake;
public RunIntakeUntilDetectedCommand(IntakeSubsystem intake) { m_intake = intake; // Lock this subsystem: interrupts any conflicting command! addRequirements(m_intake); }
@Override public void initialize() { // Runs ONCE when command starts m_intake.setVoltage(Volts.of(8.0)); }
@Override public void execute() { // Runs EVERY 20ms while active // Typically empty if running a fixed voltage or onboard closed-loop }
@Override public boolean isFinished() { // Evaluated EVERY 20ms. Return true to finish command. return m_intake.hasGamePiece(); }
@Override public void end(boolean interrupted) { // Runs ONCE when command finishes or is cancelled m_intake.setVoltage(Volts.of(0.0)); }}Purpose of Each Method:
Section titled “Purpose of Each Method:”initialize(): Prepares the mechanism for the action. Used for resetting timers, setting target setpoints, or clearing error accumulators.execute(): Continuously updates outputs. For motors running onboard PID or Motion Magic, this method is often left empty because the motor controller manages the 1 kHz closed loop internally.isFinished(): Defines the completion criteria. Returnsfalsefor continuous actions (like teleop driving) ortruewhen a condition is met (sensor tripped, target reached, or timeout expired).end(boolean interrupted): Clean-up method. Must always leave the mechanism in a safe state (e.g. cutting motor power or engaging brake mode). Theinterruptedflag istrueif another command preempted this command beforeisFinished()returnedtrue.
3. Subsystem Requirements & Mutual Exclusion
Section titled “3. Subsystem Requirements & Mutual Exclusion”The most important rule in Command-Based programming is the Mutual Exclusion Rule:
A Subsystem can only be required by ONE active Command at any given time.
When you call addRequirements(m_elevator) inside a command constructor:
- If the elevator is idle, the new command begins running immediately.
- If another command is currently controlling the elevator, the scheduler cancels the old command, calls its
end(true)method, and starts the new command. - Two commands can never fight over the same motor controller output simultaneously.
If you forget to call addRequirements(), the scheduler will allow two commands to run simultaneously on the same hardware. For example, a default “Hold Position” command will conflict with an “Elevator Move” command, causing violent motor stuttering.
4. Default Commands
Section titled “4. Default Commands”Subsystems can designate a Default Command that runs automatically whenever no other command is requiring that subsystem:
// Drivetrain default command: drive with joysticksm_drivetrain.setDefaultCommand( m_drivetrain.driveCommand( () -> -m_driverController.getLeftY(), () -> -m_driverController.getLeftX(), () -> -m_driverController.getRightX() ));
// Arm default command: hold current positionm_arm.setDefaultCommand(m_arm.holdPositionCommand());When an autonomous routine or temporary button command finishes, the subsystem automatically resumes its default command without requiring manual button presses.
5. Modern WPILib Command Patterns
Section titled “5. Modern WPILib Command Patterns”Modern WPILib releases introduce several design refinements to prevent common runtime concurrency mistakes:
Deprecation of Direct Command.schedule()
Section titled “Deprecation of Direct Command.schedule()”Directly calling myCommand.schedule() is deprecated in favor of declarative Trigger bindings or explicit scheduler calls:
// Deprecated:// myCommand.schedule();
// Preferred declarative approach in RobotContainer:m_operator.a().onTrue(myCommand);
// Explicit manual scheduling (e.g., when launching autonomous selections):CommandScheduler.getInstance().schedule(m_autonomousCommand);Direct calls on command instances bypassed requirement tracking context in multi-threaded callbacks.
Subsystem Idle Command (Subsystem.idle())
Section titled “Subsystem Idle Command (Subsystem.idle())”Subsystems now provide a built-in idle() method that returns a non-terminating command requiring the subsystem without commanding actuator outputs. This replaces ad-hoc run(() -> {}) lambdas for disabling mechanisms while reserving hardware requirements:
// Holds subsystem requirements in an idle state:m_shooter.setDefaultCommand(m_shooter.idle());Clean State Timing (Timer.createStarted())
Section titled “Clean State Timing (Timer.createStarted())”Instead of instantiating and manually triggering a timer in separate statements, use Timer.createStarted():
// Creates and starts the timer immediately in one stepprivate final Timer m_watchdogTimer = Timer.createStarted();Common Failure Modes
Section titled “Common Failure Modes”1. Motor Keeps Spinning After Button Released
Section titled “1. Motor Keeps Spinning After Button Released”- Symptom: Motor continues running indefinitely after releasing controller button.
- Cause: Command lacked an
end()implementation, or motor power was not zeroed wheninterrupted == true. - Fix: Always set motor voltage to zero in
end(boolean interrupted).
2. Command Finishes Immediately
Section titled “2. Command Finishes Immediately”- Symptom: Button is pressed, but mechanism barely twitches and stops.
- Cause:
isFinished()returnedtrueon the very first loop cycle (for example, sensor was already tripped or variable initialized improperly). - Fix: Check that
isFinished()logic properly verifies setpoint arrival or sensor debounce.
Check Your Work
Section titled “Check Your Work”- Write a test command in simulation with logging inside each lifecycle method:
System.out.println("Init");System.out.println("End: interrupted=" + interrupted);
- Schedule the command, interrupt it with a second command, and verify that
end(true)executes before the second command’sinitialize().
Verified Sources & Standards
- WPILib Command-Based Programming Lifecycledocs.wpilib.orgWPILib Standard
- WPILib Yearly Changelogdocs.wpilib.orgWPILib Standard