> For the complete documentation index, see [llms.txt](https://docs.raidrobotics.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.raidrobotics.org/commands-v3-state-machine/concepts/commands-v3.md).

# Commands v3 in this project

The template is built on **Commands v3**, the version of WPILib's command framework that ships with WPILib 2027. If you've used Commands v2 (`Subsystem`, `Command`, `SequentialCommandGroup`), most of the ideas carry over, but the way you write commands is different.

This page covers only the parts of Commands v3 that the template uses. For the full framework, see the [WPILib Commands v3 docs](https://docs.wpilib.org/en/latest/docs/software/commandbased/commands-v3/index.html).

## Mechanisms

A **mechanism** is a piece of hardware that only one command may use at a time. It's the v3 name for what v2 called a subsystem. A class becomes a mechanism by implementing `Mechanism`:

{% code title="Mechanism1.java" %}

```java
public class Mechanism1 implements Mechanism {
    private final TalonFX motor = new TalonFX(Constants.CAN.MECHANISM_1_MOTOR, Constants.CAN.MECHANISM_BUS);
    ...
}
```

{% endcode %}

In the template, `Mechanism1`, `Mechanism2` and `CommandSwerveDrivetrain` are mechanisms. `Superstructure` and `Vision` are **not**: they have no motors of their own, so nothing ever needs to require them.

### No `periodic()`

Commands v3 mechanisms have no `periodic()` method to override. Any class that needs to run code every loop registers its own with the scheduler, usually in the constructor:

```java
Scheduler.getDefault().addPeriodic(this::periodic);
```

Every class in the template that logs does this: the mechanisms, the drivetrain, `Superstructure`, `Vision` and `SuperstructureSim`.

## Writing commands

### A command that repeats every loop

Most mechanism commands do one thing every loop until something else takes over. Use `runRepeatedly`:

{% code title="Mechanism1.java" %}

```java
public Command goTo(String name, Supplier<Angle> angle) {
    return runRepeatedly(() -> {
        target = angle.get();
        motor.setControl(request.withPosition(target));
    }).named("Mechanism1." + name);
}
```

{% endcode %}

`runRepeatedly` requires the mechanism it's called on, and it never ends on its own. That's on purpose: in this project, the state machine decides when to move on, not the mechanism.

### A command with steps

When a command does one thing, then another, write it as an ordinary method body with `run(coroutine -> ...)`. Call `coroutine.yield()` wherever the command should wait for the next loop:

{% code title="Mechanism2.java" %}

```java
public Command eject() {
    return run(coroutine -> {
        while (hasGamePiece()) {                    // step 1: until the piece clears the sensor
            set(EJECT_VOLTAGE);
            coroutine.yield();
        }
        final double stopAt = Utils.getCurrentTimeSeconds() + EJECT_EXTRA_TIME.in(Seconds);
        while (Utils.getCurrentTimeSeconds() < stopAt) {    // step 2: a little longer
            set(EJECT_VOLTAGE);
            coroutine.yield();
        }
    }).named("Mechanism2.Eject");
}
```

{% endcode %}

The command ends when the method returns. This replaces most of v2's `SequentialCommandGroup`, `WaitUntilCommand` and `FunctionalCommand`.

{% hint style="warning" %}
Every loop inside a coroutine **must** call `coroutine.yield()` (or another `coroutine` method that waits). A `while` loop without one never gives control back, and the whole robot program freezes.
{% endhint %}

### A command that requires nothing

Some commands don't move hardware: they set a flag, reset a pose, or run other commands. Make them with `Command.noRequirements(...)` so they never interrupt anything:

{% code title="CommandSwerveDrivetrain.java" %}

```java
public Command seedFieldCentricCommand() {
    return Command.noRequirements(coroutine -> seedFieldCentric())
        .named("Drivetrain.SeedFieldCentric");
}
```

{% endcode %}

The [request commands](https://docs.raidrobotics.org/commands-v3-state-machine/concepts/requests.md) and the auto routines are all built this way.

### Waiting on other commands

Inside a coroutine, you can run other commands and wait for them:

| Call                                   | Means                                               |
| -------------------------------------- | --------------------------------------------------- |
| `coroutine.yield()`                    | Wait for the next loop.                             |
| `coroutine.waitUntil(() -> condition)` | Wait until the condition is true.                   |
| `coroutine.await(command)`             | Run this command and wait until it's done.          |
| `coroutine.awaitAll(a, b)`             | Run these together and wait for all of them.        |
| `coroutine.park()`                     | Wait forever, until something cancels this command. |

The [example auto](https://docs.raidrobotics.org/commands-v3-state-machine/guide/autonomous.md) is written almost entirely with `await` and `awaitAll`.

### Combining commands

`Command.parallel(a, b)` runs commands at the same time. The template uses it for every superstructure state, so one state can tell every mechanism what to do:

```java
Command.parallel(
    mechanism1.goTo("Intake", Mechanism1.INTAKE),
    mechanism2.intake()
).until(this::hasGamePiece)
```

Commands passed to `parallel(...)` are **required**: the group finishes when all of them finish. Add `.optional(command)` for a command that should run alongside but not hold the group open. The SCORING state uses this so that only `eject()` has to finish.

Other decorators the template uses:

| Decorator                     | Does                                                                                         |
| ----------------------------- | -------------------------------------------------------------------------------------------- |
| `.named("Name")`              | Gives the command a name. It shows up in logs and dashboards. Name every command.            |
| `.until(() -> condition)`     | Ends the command when the condition becomes true.                                            |
| `.withTimeout(Seconds.of(3))` | Ends the command after a time limit. Use it on every auto step that waits on the real world. |
| `.whenCanceled(() -> ...)`    | Runs code if the command is canceled.                                                        |
| `.whenExited(() -> ...)`      | Runs code when the command ends normally.                                                    |

### Naming commands

Every command in the template has a name of the form `Owner.What`: `Mechanism1.Stow`, `Superstructure.RequestIntake`, `AutoDrive.ToGamePiece`. The mechanisms log the name of the command that's running, so a clear name tells you in the log *why* a mechanism moved, not just that it did.

## State machines

Commands v3 has a built-in `StateMachine` command. The template uses one for the superstructure. It gets its own page: [The superstructure state machine](https://docs.raidrobotics.org/commands-v3-state-machine/guide/superstructure.md).

## Triggers

Buttons and robot modes are **triggers**: things that start and stop commands. The template uses these:

| Binding                                                | Runs the command...                                 |
| ------------------------------------------------------ | --------------------------------------------------- |
| `controller.rightTrigger().whileTrue(cmd)`             | ...while the button is held; cancels it on release. |
| `controller.leftBumper().onTrue(cmd)`                  | ...once, when the button is pressed.                |
| `controller.view().toggleOnTrue(cmd)`                  | ...from one press until the next press.             |
| `controller.view().and(controller.y()).whileTrue(cmd)` | ...while both buttons are held.                     |
| `RobotModeTriggers.teleop().whileTrue(cmd)`            | ...for as long as teleop is enabled.                |
| `RobotModeTriggers.autonomous().whileTrue(cmd)`        | ...for as long as autonomous is enabled.            |
| `RobotModeTriggers.disabled().whileTrue(cmd)`          | ...for as long as the robot is disabled.            |

Where you create a binding matters. A binding made in an opmode only works while that opmode is selected. A binding made in `Robot.java` works all the time. See [Opmodes](https://docs.raidrobotics.org/commands-v3-state-machine/concepts/opmodes.md).

## Default commands

A mechanism's **default command** runs whenever no other command is using it. The drivetrain's default command is "drive from the joysticks", set in `DriveTeleop`:

```java
drivetrain.setDefaultCommand(
    drivetrain.applyRequest("Drivetrain.FieldCentricDrive", () -> ...)
);
```

The superstructure's mechanisms don't use default commands. The state machine is always running while the robot is enabled, and every state gives every mechanism a command.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.raidrobotics.org/commands-v3-state-machine/concepts/commands-v3.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
