Introduction to WPILib Lesson

Introduction to WPILib

WPILib is the official software library for FRC. Think of it as a massive toolbox of pre-written code that handles the complex, low-level tasks of controlling a robot, letting you focus on strategy and logic.

What is WPILib?

WPILib (Worcester Polytechnic Institute Library) provides the classes and methods needed to interact with every part of the FRC control system. Without it, you would need to write code from scratch to read a joystick or command a motor. WPILib turns these complex tasks into simple method calls.

What's in the Toolbox?

  • Hardware Classes: Classes that represent physical devices like motor controllers (`Spark`, `TalonFX`), sensors (`Encoder`, `Gyro`), and controllers (`Joystick`, `XboxController`).
  • Drivetrain Helpers: Classes like `DifferentialDrive` that simplify the math for controlling a robot's movement.
  • Driver Station Communication: The code that handles the vital link between your robot and the driver's laptop.
  • Utilities: A rich set of tools for timers, PID controllers, math functions, and more.

The Robot's Lifecycle

Your robot code doesn't just run from top to bottom. It follows a specific "lifecycle" managed by WPILib. The main `Robot.java` class contains special methods that are automatically called at different stages of a match.

public class Robot extends TimedRobot {

    // Called ONCE when the robot is first turned on.
    // Use this for all your initial setup.
    @Override
    public void robotInit() {
        // Create motor and sensor objects here
    }

    // Called 50 times per second during the autonomous period.
    @Override
    public void autonomousPeriodic() {
        // Autonomous logic goes here
    }

    // Called 50 times per second during the driver-controlled period.
    @Override
    public void teleopPeriodic() {
        // Read joystick values and update motors here
    }

    // Called when the robot is disabled.
    @Override
    public void disabledInit() {
        // Code to run once when disabled
    }

    // ... other lifecycle methods ...
}
    

The Periodic Methods

The methods ending in `Periodic` (like `teleopPeriodic` and `autonomousPeriodic`) are the heartbeat of your robot. They are called by WPILib approximately every 20 milliseconds (50 times per second). This constant, rapid loop is where you continuously check sensors and update motor speeds.

Test Your Knowledge

Question: You need to create the object for your drivetrain's main motor controller. In which lifecycle method should this one-time setup code be placed?