> 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/guide/autonomous.md).

# Autonomous

An auto in this template is two commands running side by side for the whole autonomous period:

1. **The superstructure's state machine**, exactly as in teleop.
2. **The routine**: a list of steps, read top to bottom, that plays the part of the driver. It drives the robot with `AutoDrive`, and makes the same requests the driver's buttons make.

Because the routine only makes requests, an auto can't do anything to a mechanism that teleop couldn't, and everything learned tuning one carries to the other.

| File                              | What it is                                                       |
| --------------------------------- | ---------------------------------------------------------------- |
| `opmodes/auto/ExampleAuto.java`   | **Template:** score the preload, fetch a game piece, score again |
| `opmodes/auto/DoNothingAuto.java` | The auto that does nothing. Always keep it.                      |
| `auto/AutoDrive.java`             | "Drive to this pose", for autos                                  |

## The example auto

{% code title="ExampleAuto.java" lineNumbers="true" %}

```java
@Autonomous(name = "Example: Score, Fetch, Score")
public class ExampleAuto implements OpMode {
    private static final Pose2d START = new Pose2d(2.0, 4.0, Rotation2d.ZERO);
    private static final Pose2d GAME_PIECE = new Pose2d(4.0, 4.5, Rotation2d.ZERO);

    public ExampleAuto(Robot robot) {
        final AutoDrive drive = robot.autoDrive;
        final Superstructure superstructure = robot.superstructure;

        final Command routine = Command.noRequirements(coroutine -> {
            // 1. Tell the drivetrain where the robot was placed
            coroutine.await(drive.resetPose(START));

            // 2. Score the preload
            coroutine.await(superstructure.scoreUntilDone().withTimeout(Seconds.of(3)));

            // 3. Drive to the game piece with the intake running, until we arrive AND have it
            coroutine.awaitAll(
                drive.driveTo("ToGamePiece", GAME_PIECE).withTimeout(Seconds.of(4)),
                superstructure.intakeUntilHolding().withTimeout(Seconds.of(5))
            );

            // 4. Drive back
            coroutine.await(drive.driveTo("ToScore", START).withTimeout(Seconds.of(4)));

            // 5. Score it (scoreUntilDone skips itself if step 3 came back empty-handed)
            coroutine.await(superstructure.scoreUntilDone().withTimeout(Seconds.of(3)));
        }).named("ExampleAuto");

        // Both run for as long as autonomous is enabled, and stop when it ends
        RobotModeTriggers.autonomous().whileTrue(superstructure.createStateMachine());
        RobotModeTriggers.autonomous().whileTrue(routine);

        RobotModeTriggers.autonomous().whileTrue(robot.vision.ignore());
    }
}
```

{% endcode %}

(The real file also logs an event at each step. It's trimmed here.)

### Writing the routine

Inside the routine:

* `coroutine.await(command)` means "run this and wait until it's done".
* `coroutine.awaitAll(a, b)` means "run these together and wait for both".

It's ordinary Java in between, so `if`, loops and variables all work:

```java
if (!superstructure.hasGamePiece()) {
    // ...go for a different piece...
}
```

The routine is built with `Command.noRequirements`. It doesn't need the drivetrain or the mechanisms itself: `driveTo` requires the drivetrain, and the state machine's states require the mechanisms.

### Timeouts on every step

Give every step that waits on the real world a timeout. A missed game piece should cost a second, not the rest of the auto. In step 3, the drive and the intake run together and each has its own timeout, so the robot moves on when both are done or have given up.

### The auto requests

Autos use the versions of the requests that **end when the job is done**:

| Request                               | Ends when                                                                                                     |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `superstructure.intakeUntilHolding()` | The state machine reaches HOLDING                                                                             |
| `superstructure.scoreUntilDone()`     | The state machine has gone through SCORING and left it. Skips itself (and logs why) if there's no game piece. |

See [Requests](https://docs.raidrobotics.org/commands-v3-state-machine/concepts/requests.md#requests-for-autos).

### Vision in autos

Autos drive on wheels and gyro alone, as in 2026: one bad camera estimate mid-routine moves every pose after it. The last line of the constructor holds the `vision.ignore()` request for the whole autonomous period. Vision comes back by itself when auto ends.

Delete that line if an auto needs the cameras: a long routine where the wheels drift, or aiming at a tag.

## AutoDrive

`AutoDrive` is the driving half of an auto: "go to this spot on the field". It's the simplest thing that works: three PID loops (x, y and heading) that push the robot straight at a target pose and stop when it's close. There are no path files and no planner, and every piece of it is in one file.

### Commands

| Command                   | Does                                                                                                                                                                           |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `resetPose(bluePose)`     | Tells the drivetrain "you are here". The first step of every auto: the robot can't know where it was placed until it sees an AprilTag, and it may not see one before it moves. |
| `driveTo(name, bluePose)` | Drives straight to a pose and ends when the robot is there. Shows up in the log as `AutoDrive.name`.                                                                           |

`driveTo` requires the drivetrain, so it takes over from the default drive command while it runs.

### Poses are written for the blue alliance

Autos give every pose as if the robot were on blue: the origin is at blue's right corner, +X points toward red, and +Y points to the left. `AutoDrive.forAlliance(pose)` mirrors it when the robot is on red, so one routine works on both sides.

```java
public static Pose2d forAlliance(Pose2d bluePose) {
    final boolean isRed = MatchState.getAlliance().orElse(Alliance.BLUE) == Alliance.RED;
    if (!isRed) {
        return bluePose;
    }
    return new Pose2d(
        Constants.Field.LENGTH_METERS - bluePose.getX(),
        Constants.Field.WIDTH_METERS - bluePose.getY(),
        bluePose.getRotation().plus(Rotation2d.k180deg)
    );
}
```

`driveTo` and `resetPose` work out the alliance when the command **starts**, not when the auto is built, because the alliance isn't known until the Driver Station connects.

{% hint style="warning" %}
This assumes the field is **rotated** 180° between alliances, like 2022 to 2026, and uses the 2026 field size. When the 2027 game is released, check both. If the field is flipped like a mirror instead, change only `forAlliance`.
{% endhint %}

### Tuning

| Setting                       | Value | Notes                                                           |
| ----------------------------- | ----- | --------------------------------------------------------------- |
| `MAX_SPEED_METERS_PER_SECOND` | 2.5   | Start slow. An auto that arrives is worth more than a fast one. |
| `MAX_TURN_RADIANS_PER_SECOND` | π     |                                                                 |
| `POSITION_TOLERANCE_METERS`   | 0.05  | How close counts as "arrived"                                   |
| `HEADING_TOLERANCE_RADIANS`   | 3°    |                                                                 |
| x and y `kP`                  | 4.0   | (m/s) per meter of error                                        |
| Heading `kP`                  | 5.0   | (rad/s) per radian of error                                     |

`AutoDrive` logs `Auto/Target Pose` and `Auto/Distance To Target (m)`. Compare the target with `Drive/Pose` in AdvantageScope to see how it's tracking.

### Growing past this

* **Curved or timed paths**: PathPlanner or Choreo, once they support Commands v3. Their "follow path" command replaces `driveTo`, and nothing else in the autos changes.
* **Avoiding obstacles**: add waypoints, as several `driveTo`s in a row with a loose tolerance on the ones in the middle.
* **Faster arrival**: raise the speed limit and gains. Switch the x and y loops to a `ProfiledPIDController` if it overshoots.

## Making a new auto

Copy `ExampleAuto.java`, rename the class, change the `@Autonomous` name, and change the poses and steps. No other file needs to know about it. The full walkthrough is in [Write an auto](https://docs.raidrobotics.org/commands-v3-state-machine/how-to/write-an-auto.md).


---

# 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/guide/autonomous.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.
