Introduction to Autonomous Code Lesson

Introduction to Autonomous Code

For the first 15 seconds of every match, robots operate entirely on their own. A reliable, high-scoring autonomous routine is often the deciding factor in winning, and it's where all our programming concepts come together.

The Goal: Repeatable and Reliable Actions

Unlike teleop, an autonomous routine must be perfectly predictable. We can't simply tell a motor to "run for 2 seconds" and hope for the best, because factors like battery voltage and field friction make timed movements unreliable.

The Core Principles of a 2910 Autonomous

  1. Sensor-Based Movements: Every action is tied to sensor feedback. We don't drive "for 2 seconds"; we drive "until the encoder reads 36 inches."
  2. Command-Based Structure: We break down our routine into a series of small, reusable, and testable commands.

Building Blocks of an Autonomous Routine

An autonomous routine is built by stringing together individual commands. A simple task like "drive forward and grab a game piece" would be broken down into distinct commands:

  • `ResetEncodersCommand`: A command to zero out the drivetrain encoders.
  • `DriveDistanceCommand`: A command that drives until the encoders reach a target distance.
  • `IntakeCommand`: A command that runs the intake until a sensor detects a game piece.

Command Groups: The Choreography of Autonomous

We use Command Groups to string these individual commands together into a seamless routine. The most common type is a `SequentialCommandGroup`, which runs commands one after another.

// In RobotContainer.java

// This method builds and returns our complete autonomous routine.
public Command getAutonomousCommand() {
    // We assume we have created simple, sensor-based commands like:
    // - DriveDistanceCommand(m_drivetrain, 36.0)
    // - TurnToAngleCommand(m_drivetrain, 90.0)
    // - IntakeCommand(m_intake)

    // A SequentialCommandGroup runs each command in order, waiting for the
    // previous one to finish before starting the next.
    return new SequentialCommandGroup(
        new ResetEncodersCommand(m_drivetrain),
        new DriveDistanceCommand(m_drivetrain, 36.0),
        new IntakeCommand(m_intake),
        new TurnToAngleCommand(m_drivetrain, 90.0)
    );
}
    

Notice how readable this is! The code reads like a set of plain English instructions. We hide all the complex logic inside individual commands and then assemble them in a clean, understandable sequence. This is the power of the Command-Based model.

Test Your Knowledge

Question: Why is it better to use an encoder to drive a specific distance in autonomous mode instead of running the motors for a set amount of time?