Sensor-Based Movement Lesson

Sensor-Based Movement: The 2910 Standard

Timed movements are a good start, but for competition-level precision and reliability, we use sensor-based movements. This means we command the robot to act until a sensor tells it to stop, creating a "closed-loop" system that is accurate and repeatable.

The Core Principle: Feedback from the Real World

The philosophy is to make decisions based on real-world feedback, not blind guesses about timing. This makes our autonomous routines resilient to the unpredictable conditions of a real match.

  • Instead of: "Drive forward at 50% speed for 1.5 seconds."
  • We say: "Drive forward at 50% speed until the drivetrain encoders have measured a distance of 36 inches."

Why This is the Standard

Using sensors makes our commands intelligent. They automatically adapt to real-world conditions.

  • If the battery voltage is low, a sensor-based command simply runs the motors for a little longer to cover the same distance.
  • If another robot bumps us, the gyroscope can correct our heading.

This commitment to feedback-driven control is a core reason for our team's consistent success.

Building a Sensor-Based Command

Let's build one of the most common and important autonomous commands: a `DriveDistanceCommand`. This command will drive the robot a specified distance and then stop, using encoder feedback to know when it's done.

public class DriveDistanceCommand extends Command {
    private final DriveSubsystem m_drive;
    private final double m_distance;
    private final double m_speed;

    public DriveDistanceCommand(DriveSubsystem drive, double distance, double speed) {
        m_drive = drive;
        m_distance = distance;
        m_speed = speed;
        addRequirements(m_drive);
    }

    @Override
    public void initialize() {
        // Reset the encoders to 0 at the start of the command
        m_drive.resetEncoders();
        m_drive.setSpeed(m_speed); // Start driving
    }

    // This is the key: the command is finished when the encoder reading
    // is greater than or equal to the target distance.
    @Override
    public boolean isFinished() {
        return m_drive.getDistance() >= m_distance;
    }

    @Override
    public void end(boolean interrupted) {
        // Stop the motors when the command ends
        m_drive.stop();
    }
}
    

Test Your Knowledge

Question: In a sensor-based `DriveDistanceCommand`, which command lifecycle method is responsible for checking the encoder to see if the robot has reached its target?