How to do an if/else if/else in command based programming

So our team’s new to doing command based programming. We’re learning by translating our previous years code. However, we are stuck with trying to translate the following code:

      if (m_controller.getYButton() || m_controller_right.getYButton()) {
        arm.intakeBelt();
      } else if (m_controller_right.getAButton()) {
        arm.closeGripper();
      } else {
        arm.beltStop();
      }

What is the best way to implement this kind of logic using commands?

I’m not sure if this misses the point of “translating to commands”, but if I were writing this, say, inside of a SequentialCommandGroup, I’d just wrap the entire block as-is in an InstantCommand:

new InstantCommand(() -> {
    if (...) {
        
    } else {
    
    }
})

No need to replicate the logic with command compositions.

What you’re doing right now has a better way to be done entirely: through CommandXboxController. See Binding Commands to Triggers — FIRST Robotics Competition documentation.

Otherwise, use ConditionalCommand.

5 Likes

Trigger composition is written to do exactly this.

3 Likes

If you need the EXACT logic where intakeBelt will also run if you press button A while pressing any of the other Ys

ButtonY.or(buttonY_right).whileTrue(Commands.run(arm::intakeBelt , arm));
ButtonA.and(ButtonY.or(buttonY_right).negate()).whileTrue(Commands.run(arm::closeGripper, arm));

arm.setDefaultCommand(Commands.run(arm::beltStop , arm));

But you can remove the button negation for close gripper and probably end up with desired behavior.

Is there a reason that closing the gripper and running the belt are mutually exclusive? If they are unrelated hardware wise, you may want to separate the arm subsystem to belt and gripper so the command scheduler can be more granular.

All the buttons are Trigger objects. You can get them from the various command controllers in wpilib like command xbox controller.

2 Likes

If/else if/else isn’t the proper way to think about things in command-based.

Triggers → Actions is what you’re looking for here.

I recently stumbled across this resource that has some pretty solid explanations, succinct, and nice pictures: (specific to triggering commands)

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.