Robot.java Lesson

Robot.java: The Director of the Show

Every FRC robot project has a `Robot.java` file. It's the main entry point for your code and serves as the manager for the robot's entire lifecycle, telling different parts of your code when to run during a match.

The Robot's Lifecycle Methods

Think of a match as a play with different acts (autonomous, teleop, disabled). `Robot.java` is the director who calls out the cues for each act. It contains special methods that WPILib calls automatically at the right times.

Key Lifecycle Methods

  • `robotInit()`: Called once when the robot is first turned on. Perfect for one-time setup.
  • `autonomousInit()` / `autonomousPeriodic()`: Called once at the start of auto, and then repeatedly every 20ms during auto.
  • `teleopInit()` / `teleopPeriodic()`: Called once at the start of teleop, and then repeatedly every 20ms during teleop.
  • `disabledInit()` / `disabledPeriodic()`: Called when the robot is disabled.
  • `robotPeriodic()`: Called repeatedly (every 20ms) during all modes of operation.

The Modern Role of `Robot.java`

In the past, programmers would fill the `teleopPeriodic` and `autonomousPeriodic` methods with lots of complex logic. However, with the modern Command-Based Framework that we use, `Robot.java` has become much simpler.

Its only two jobs now are:

  1. To create a single, all-important object: the `RobotContainer`.
  2. To tell the `CommandScheduler` to run over and over again.

The `Robot.java` file is now just a clean, simple starting point. All the complex logic for subsystems, commands, and button bindings is neatly organized in other files.

public class Robot extends TimedRobot {
    private Command m_autonomousCommand;
    private RobotContainer m_robotContainer;

    // 1. Create the RobotContainer
    @Override
    public void robotInit() {
        // This is the most important line in robotInit().
        // It creates the central hub for our entire robot's code.
        m_robotContainer = new RobotContainer();
    }

    // 2. Run the CommandScheduler
    @Override
    public void robotPeriodic() {
        // This is the most important line in robotPeriodic().
        // It's the engine that makes the entire Command-Based system work.
        CommandScheduler.getInstance().run();
    }

    @Override
    public void autonomousInit() {
        m_autonomousCommand = m_robotContainer.getAutonomousCommand();
        if (m_autonomousCommand != null) {
            m_autonomousCommand.schedule();
        }
    }

    // ... other lifecycle methods are often empty in a command-based project ...
}
    

Test Your Knowledge

Question: In a modern command-based robot project, what is the most important line of code inside the `robotPeriodic()` method?