RLD 5: Joysticks and Buttons - TEAM1771/Crash-Course GitHub Wiki

Getting data from driver controllers is essential for controlling robots.

Generic frc::Joystick

The joystick class refers to any type of controller/joystick and can be included as follows:

#include <frc/Joystick.h>

Initialize Joystick: Declare a joystick object to interface with your driver station's game controller.

frc::Joystick joystick{0};  // Replace '0' with the USB port number of your controller which can be found in DriverStation

Accessing Joystick values

Getting data directly from the joysticks is very simple.

frc::Joystick joystick{0};

double x_joy = joystick.GetX(); // Refers to the left/right of joystick
double y_joy = joystick.GetY(); // Refers to the up/down of josytick

Buttons

To access button states, you can use the GetRawButton method on the joystick object. For example, to check if button 1 (A button on an Xbox controller) is pressed, you can use:

bool is_button_pressed = driver_controller.GetRawButton(1); // You can check which number refers to which button using DriverStation

Respond to Button Press: You can use the button states to trigger actions in your robot code. For example, to control a motor when button 1 is pressed, you might do something like this in your robot's TeleopPeriodic method:

if (driver_controller.GetRawButton(1)) 
{
    // Perform an action, e.g., start a motor
} else 
{
    // Stop the motor
}

Controllers

You might have noticed that frc::Joystick's don't seem like they would be a good fit for modern game controllers. First, there would be a lot of copy-pasting if you wanted to check a button in multiple different places in code. Plus, every time you wanted to use a new button, you would need to look up the number that maps to that button that controller. Additionally, controllers usually have multiple joysticks, as well as triggers, buttons, etc.

Thankfully, WPILib has included a XboxController and PS4Controller class that are better suited to the types of controllers we commonly use.

#include <frc/PS4Controller.h>

frc::PS4Controller ps4{0};

Now, in a function like TeleopPeriodic(), you can directly refer to the buttons on the controller.

if(ps4.GetTriangleButton())
{
    // Run a motor
}
else
{
    // Stop
}

You can also check the various different joysticks/triggers on the controller.

double left_x = driver.GetLeftX(); // Left/right on the left joystick
double right_y = driver.GetRightY(); // Up/down on the right joystick

double right_trigger = driver.GetR2Axis();

Extra Resources

Refer to the WPILib documentation for more in-depth information and examples.