Running commands on Joystick input

You can cause commands to run when joystick buttons are pressed, released, or continuously while the button is held down. This is extremely easy to do only requiring a few lines of code.

The OI Class

The OI Class

The command based template contains a class called OI, located in OI.java, where Operator Interface behaviors are typically defined. If you are using RobotBuilder this file can be found in the org.usfirst.frc####.NAME package

Create the Joystick object and JoystickButton objects

Create the Joystick object and JoystickButton objects

In this example there is a Joystick object connected as Joystick 1. Then 8 buttons are defined on that joystick to control various aspects of the robot. This is especially useful for testing although generating buttons on SmartDashboard is another alternative for testing commands.

Associate the buttons with commands

Associate the buttons with commands

In this example most of the joystick buttons from the previous code fragment are associated with commands. When the associated button is pressed the command is run. This is an excellent way to create a teleop program that has buttons to do particular actions.

Other options

In addition to the "whenPressed()" condition showcased above, there are a few other conditions you can use to link buttons to commands:

  • Commands can run when a button is released by using whenReleased() instead of whenPressed().
  • Commands can run continuously while the button is depressed by calling whileHeld().
  • Commands can be toggled when a button is pressed using toggleWhenPressed().
  • A command can be canceled when a button is pressed using cancelWhenPressed().

Additionally commands can be triggered by arbitrary conditions of your choosing by using the Trigger class instead of Button. Triggers (and Buttons) are usually polled every 20ms or whenever the scheduler is called.