wiki:ControlSystems/SoftwareTeam/Training/GettingStarted/Debouncing

Version 1 (modified by David Albert, 5 years ago) (diff)

--

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:

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

...
public void robotInit() {
   xbox = new XboxController(0);
   debounce = new Timer();
   debounce.start();
}

public void robot.periodic() {
   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();
       }
   }
}