Command-Based Programming
Mediumdifficulty
State machines are great for one subsystem with clear modes. Command-based programming earns its keep when several subsystems have to work together. A command is one reusable action, like "drive to this pose" or "raise the lift," and an autonomous routine is a combination of commands.
The step-counter autonomous
Most teams eventually write something like this:
switch (step) {
case 0:
driveToSpikeMark();
if (drive.atTarget()) step++;
break;
case 1:
liftToScore();
if (lift.atTarget()) step++;
break;
case 2:
openClaw();
if (timer.seconds() > 0.4) step++;
break;
}
This works until you want the lift to rise while the drivetrain is still moving. Now step == 0 means
"drive, and maybe lift." Then you want to aim while lifting, and cancel everything if localization
fails, and the step counter turns into a pile of special cases.
Command-based code stops asking "which numbered step am I on?" and asks "which commands are running right now, and which subsystems does each one need?" That second question copes with two things happening at once on different subsystems and finishing at different times, which a step counter can't.
The scheduler's view
Each bar in the demo is a command. Commands that need different subsystems can run at the same time. Commands that need the same subsystem can't both control it.
Switch the lift-and-aim section between sequential and parallel. The robot does the same work either way. In parallel mode it just uses independent subsystems at the same time.
What a command is
Every command goes through the same four calls:
| Method | Called | Purpose |
|---|---|---|
initialize() | once, when scheduled | capture targets, reset timers, prepare hardware |
execute() | every loop while active | do one non-blocking slice of work |
isFinished() | every loop after execute() | report whether the command is done |
end(interrupted) | once, after finish or cancellation | stop motors, hold position, clean up |
Each loop, the scheduler goes through every running command once: call execute(), then ask
isFinished(). Because it visits every command every loop, one command that blocks stalls all of them.
The scheduler also keeps commands from fighting. Each command lists the subsystems it needs. Say
DriveToPose needs {drive} and RaiseLift needs {lift}. They share nothing, so they can run
together. A second command that also needs {lift} can't run alongside RaiseLift, because both would
write to the lift motor in the same loop, so the scheduler has to pick one. (In set notation, two
commands conflict when .)
Groups are commands too
A group has the same four calls as a single command, so it can be scheduled, interrupted, and checked for conflicts the same way.
| Group | Behavior | FTC use case |
|---|---|---|
| Sequential | run command A, then B, then C | drive, score, park |
| Parallel | run A and B at the same time | drive while raising lift |
| Race | the first child to finish ends the group and interrupts every unfinished child | drive or timeout, whichever finishes first |
| Deadline | one designated child ends the group and interrupts the rest; other children may finish early without ending it | drive to pose while running intake |
And since groups are commands, groups can contain groups. That's how a full autonomous stays readable without turning into one enormous class.
Writing commands
The interface itself is small:
public interface Command {
void initialize(); // once, when the command starts
void execute(); // one loop of work; must return fast
boolean isFinished(); // true when the goal is met
void end(boolean interrupted); // once, whether finished or cancelled
Set<Subsystem> getRequirements(); // subsystems it needs exclusively
}
WPILib's Command has the same five pieces. (It became an abstract class rather than an interface in
2024 so WPILib could put decorator methods on it.)
What breaks if you delete each one?
- no
initialize()— where does one-time setup go, and what happens if you put it at the top ofexecute()? - no
isFinished()— how does anything ever move on? - no
end()— a command is cancelled halfway. Who stops the motor? - no
getRequirements()— two commands both want the lift. What happens?
Then the subtle one: find a case where a command should clean up differently after being cancelled
than after succeeding. That is what the Setup at the top of For interrupted flag is for.Show solution
execute() runs every loop, so a command that resets a timer or captures a
starting pose would reset it forever and never finish. Without isFinished() the scheduler has no
completion signal, and you are back to polling from the caller. Without end() a cancelled command
leaves its motor at whatever power it last set — the lift keeps climbing after you let go of the
button. Without requirements, two commands write conflicting powers to the same motor every loop and
the mechanism buzzes.interrupted: a command that drives to a pose should hold that pose when it succeeds, but stop
the drivetrain when it is cancelled — because whatever cancelled it is about to take the drivetrain
somewhere else.
A command should do one job and expose its requirement clearly:
public final class RaiseLift implements Command {
private final Lift lift;
private final double targetInches;
public RaiseLift(Lift lift, double targetInches) {
this.lift = lift;
this.targetInches = targetInches;
}
public void initialize() { lift.setTargetHeight(targetInches); }
public void execute() { lift.updateController(); }
public boolean isFinished() { return lift.atTarget(); }
public void end(boolean cancelled) { lift.holdCurrentPosition(); }
public Set<Subsystem> getRequirements() { return Collections.singleton(lift); }
}
There's no PID math, no motor call, and no encoder conversion in it. It tells a subsystem that already knows how to control itself what to do, so the same class can raise to a low junction, a high junction, or back to the floor.
Each of these belongs either in RaiseLift or in Lift. Which, and why?
- the target height for the high junction
kPfor the lift controller- the decision to raise now
- converting inches to encoder ticks
Show solution
The high-junction height and the decision to raise now belong to the command, because they're about
this particular routine. kP and the inch-to-tick conversion belong to Lift, because they're facts
about the hardware that don't change between routines. A useful test: would a second command using
the same mechanism need a different answer?
A lift gets interrupted at full extension, and It falls. Gravity is still there and nothing is pushing back, so the lift slams down, usually onto
whatever the claw was about to score on. end() sets the power to zero instead of holding. What
happens?Show solution
holdCurrentPosition() keeps the controller running with the
current height as the target. That costs a little current and keeps the lift where it was.
Now autonomous can be written as composition:
Command scorePreload = new SequentialCommandGroup(
new ParallelCommandGroup(
new DriveToPose(drive, scoringPose),
new RaiseLift(lift, HIGH_JUNCTION)),
new ScoreGameElement(claw),
new ParallelCommandGroup(
new RetractLift(lift),
new DriveToPose(drive, parkPose)));
scheduler.schedule(scorePreload);
while (opModeIsActive()) {
drive.updatePoseEstimate();
scheduler.run(); // advances whatever commands are active
telemetry.update();
}
The routine reads like a description of what the robot does. Driving and lifting overlap because they use different subsystems, and scoring waits because it comes after the parallel group. With the four lifecycle calls, requirements, and sequential and parallel groups, you can already write a complete non-blocking autonomous.
A sequential group starts each command when the previous one finishes. A parallel group runs them all at once and finishes when... when what? Come up with at least two reasonable answers and a situation where each one is right. Then check what WPILib provides.
Also: two scheduled commands both need the lift. What can the scheduler do, and which would you want
in the middle of a match? "All of them finish" is the safe default; "the first one finishes" is what you want when a drive should
cancel a lift that is merely opportunistic; "one designated command finishes" is what you want when the
drive is the real task and the lift is along for the ride. WPILib ships exactly these three:
For the conflict, the scheduler can refuse the new command or cancel the old one. During a match you
almost always want the newest one to win, since it's what the driver just asked for. That means every
command has to handle being cancelled cleanly, which is what Show solution
ParallelCommandGroup, ParallelRaceGroup, and ParallelDeadlineGroup.end(interrupted) is for.
FTC command frameworks
You can write your own scheduler, but it's worth looking at the existing FTC frameworks first. They all implement the same ideas as this lesson: commands, requirements, groups, trigger bindings, and a scheduler that runs every loop. The table below isn't a ranking, just the tradeoffs.
| Framework | Best fit | Main idea | Cost |
|---|---|---|---|
| FTCLib | Understanding the original FTC command-based ecosystem | WPILib-style commands and scheduler ported into FTC | Older baseline; many teams now prefer maintained forks |
| SolversLib | Teams that want FTCLib-style command-based with active maintenance | Updated maintained fork of older FTCLib, designed to avoid breaking most existing FTCLib code | Still inherits the WPILib/FTCLib mental model |
| Mercurial | Experienced teams that want powerful composition and better developer ergonomics | Lambda-first command builders, command groups, run states, requirements, interruptibility, and stronger diagnostics | Harder first setup and a more abstract API |
| Ivy | Pedro Pathing teams that want command-based autonomous without much ceremony | Lightweight command-based control flow library built by the Pedro Pathing ecosystem | Newer, smaller ecosystem than FTCLib-style frameworks |
FTCLib: the historical FTC command baseline
FTCLib is the vocabulary source for many FTC command-based projects: Command, Subsystem,
CommandScheduler, command groups, default commands, and subsystem requirements. Its scheduler docs
are still useful for learning the loop sequence, but for new robots treat it as the older baseline
and compare it against SolversLib before committing.
SolversLib: maintained FTCLib-style command-based
SolversLib describes itself as an updated and maintained fork of
older FTCLib, designed to preserve most existing FTCLib code. Use it when you want the familiar
WPILib/FTCLib architecture with current maintenance: CommandOpMode, command groups, requirements,
and default commands without asking the team to learn a more abstract framework.
Mercurial: powerful composition for advanced teams
Mercurial is also command-based, but it is not a
simple FTCLib clone. It pushes teams toward Lambda and StatefulLambda builders, command utilities
like Parallel, Sequential, Race, Wait, and IfElse, plus stronger error messages and a
unit-tested scheduler. Use it when your programmers are already comfortable with lambdas,
requirements, interruptibility, and builder-style APIs; otherwise the abstraction can become noise.
Ivy: command-based control flow for Pedro Pathing
Ivy is Pedro Pathing's command-based control flow library. Pedro's
own autonomous examples recommend Ivy for composing follow commands with subsystem actions. If your
robot already uses Pedro, Ivy is the low-friction way to write autos as sequential and parallel
command compositions instead of manually managing path state.
Use Ivy when your main architecture question is:
"How do I make Pedro paths and mechanism actions compose cleanly?"
Use SolversLib or Mercurial when your main architecture question is broader:
"How do I organize the whole robot's teleop, autonomous, triggers, and subsystems around commands?"
Pick the framework your programmers can actually read and debug. A simple scheduler used well beats a powerful framework nobody on the team understands.
Common mistakes
The scheduler only knows about conflicts that commands declare. If two commands both drive the
drivetrain and one forgot to require drive, they will fight and nothing will stop them.
execute() should do one loop's worth of work and return. No sleep(), no long while loops, no
waiting on a sensor. Put the "am I done?" check in isFinished().
A subsystem can use a state machine internally and still expose commands externally. For example, an
intake may have IDLE, INTAKING, and JAM_CLEARING states, while autonomous schedules simple
commands like RunIntakeUntilLoaded.
Which one to use
Use a state machine when one subsystem has a few exclusive modes. Use commands when you need to sequence, overlap, cancel, and reuse actions across several subsystems. Most good FTC code does both: state machines inside the complicated subsystems, and commands on top for autonomous and driver actions.
Either way, everything depends on knowing how long your loop takes, which is where the next lesson, From Math to a Loop, picks up.
- FTCLib Command-Based Documentation - the historical FTC command-based baseline and scheduler vocabulary.
- SolversLib Documentation - maintained FTCLib-style command-based framework for FTC teams that want the familiar architecture with current upkeep.
- Mercurial Documentation - advanced command-based framework with lambda builders, decorators, requirements, and scheduler diagnostics.
- Ivy by Pedro Pathing - lightweight command-based control flow designed to compose Pedro paths with mechanism actions.
- WPILib Command-Based Programming - the original competition-robotics command architecture that many FTC frameworks adapt.