wiki:ControlSystems/SoftwareTeam/Training/GettingStarted/Debouncing

There are many cases where a mechanical switch such as a button or a limit switch literally bounces when you change its position. The process of ignoring the bouncing so you don't repeatedly act on the switch unintentionally is called de-bouncing. There are several ways to do this; one is to start a timer when the switch change is detected and then ignore any subsequent switch changes until the timer expires. The code looks like this:

package frc.robot;

import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.Timer;

public class Robot extends TimedRobot {
  XboxController xbox;
  Timer debounce;

  @Override
  public void robotInit() {
     xbox = new XboxController(0);
     debounce = new Timer();
     debounce.start();
  }
  
  @Override
  public void robotPeriodic() {
     if (xbox.getAButton()) {
         // A button pressed
         if (debounce.hasPeriodPassed(0.5)) {
             // more than half-second since last press
             System.out.println("A button pressed!");
             // restart debounce timer so we ignore presses in next half second
             debounce.reset();
         }
     }
  }
}

Try commenting out the if statement (and its closing brace) and see what happens when you press the A button.

Last modified 15 months ago Last modified on Feb 14, 2020, 1:15:14 AM