Skip to main content

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:

FTCThe step counter that starts simple
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.

Live demoThe command scheduler
DriveToPose
RaiseLift
Aim
Score
0.0 s2.9 s total
DriveLiftTurretScorer
t = 0.00 srunning: DriveToPosesubsystems busy: Drive

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:

MethodCalledPurpose
initialize()once, when scheduledcapture targets, reset timers, prepare hardware
execute()every loop while activedo one non-blocking slice of work
isFinished()every loop after execute()report whether the command is done
end(interrupted)once, after finish or cancellationstop 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 req⁡(a)∩req⁡(b)≠∅\operatorname{req}(a) \cap \operatorname{req}(b) \ne \varnothing.)

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.

GroupBehaviorFTC use case
Sequentialrun command A, then B, then Cdrive, score, park
Parallelrun A and B at the same timedrive while raising lift
Racethe first child to finish ends the group and interrupts every unfinished childdrive or timeout, whichever finishes first
Deadlineone designated child ends the group and interrupts the rest; other children may finish early without ending itdrive 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:

FTCThe Command interface
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.)

ExerciseWhat breaks without each of the five

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 of execute()?
  • 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 interrupted flag is for.

Show solution

Setup at the top of 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.

For 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:

FTCA reusable lift command
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.

ExerciseWhich side of the boundary?

Each of these belongs either in RaiseLift or in Lift. Which, and why?

  • the target height for the high junction
  • kP for 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?

ExerciseWhy end() holds rather than cuts power

A lift gets interrupted at full extension, and end() sets the power to zero instead of holding. What happens?

Show solution

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. 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:

FTCAutonomous as composed commands
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.

ExerciseWhen is a parallel group finished?

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?

Show solution

"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: ParallelCommandGroup, ParallelRaceGroup, and ParallelDeadlineGroup.

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 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.

FrameworkBest fitMain ideaCost
FTCLibUnderstanding the original FTC command-based ecosystemWPILib-style commands and scheduler ported into FTCOlder baseline; many teams now prefer maintained forks
SolversLibTeams that want FTCLib-style command-based with active maintenanceUpdated maintained fork of older FTCLib, designed to avoid breaking most existing FTCLib codeStill inherits the WPILib/FTCLib mental model
MercurialExperienced teams that want powerful composition and better developer ergonomicsLambda-first command builders, command groups, run states, requirements, interruptibility, and stronger diagnosticsHarder first setup and a more abstract API
IvyPedro Pathing teams that want command-based autonomous without much ceremonyLightweight command-based control flow library built by the Pedro Pathing ecosystemNewer, 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?"

Match the framework to the team

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​

Requirements are not optional

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.

Commands must be non-blocking

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().

State machines and commands combine cleanly

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.

Sources & references