Command-Based Intro
Overview
Command-based code splits hardware (subsystems) from behavior (commands). The scheduler runs commands, tracks subsystem ownership, and lets teleop and auto share the same command objects. It is the default layout for new WPILib projects.
If the lifecycle methods and “actions as objects” idea feel unfamiliar, read the Java lessons below first. They cover the command pattern and deferred execution without mixing in WPILib APIs.
Java background
Setting Up Your Project
Create a WPILib project with the Command Robot template. You get Robot.java, RobotContainer.java, and starter subsystem/command examples.
In VS Code: WPILib: Create a new project → Command Robot. See Project Creation for the full walkthrough.
Core Components
The four pillars:
- Subsystems: Represent hardware (e.g., Intake, Drivetrain). Handle low-level control.
- Commands: Represent actions (e.g., RunIntake, Drive). Use subsystems.
- RobotContainer: The hub. Creates subsystems and binds buttons to commands.
- Scheduler: Runs in the background, managing command execution.
Comparison
Robot.java (TimedRobot):
- All logic in one file.
- Hardware control mixed with decisions.
- Hard to reuse the same motion in teleop and auto.
Command-Based:
- Subsystems own hardware; commands own when and why.
- The same command can run from a button or an auto routine.
Command Lifecycle
-
initialize(): Run once at start. -
execute(): Run every loop (20ms). -
isFinished(): Check if done. -
end(): Run once at finish/interrupt.
Subsystem Requirements
Commands declare requirements (subsystems they use). The Scheduler ensures only one command controls a subsystem at a time, preventing conflicts (e.g., two commands trying to move the arm).