| 1 | 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: |
| 2 | |
| 3 | {{{ |
| 4 | import edu.wpi.first.wpilibj.XboxController; |
| 5 | import edu.wpi.first.wpilibj.Timer; |
| 6 | |
| 7 | ... |
| 8 | public void robotInit() { |
| 9 | xbox = new XboxController(0); |
| 10 | debounce = new Timer(); |
| 11 | debounce.start(); |
| 12 | } |
| 13 | |
| 14 | public void robot.periodic() { |
| 15 | if (xbox.getAButton()) { |
| 16 | // A button pressed |
| 17 | if (debounce.hasPeriodPassed(0.5)) { |
| 18 | // more than half-second since last press |
| 19 | System.out.println("A button pressed!"); |
| 20 | // restart debounce timer so we ignore presses in next half second |
| 21 | debounce.reset(); |
| 22 | } |
| 23 | } |
| 24 | } |
| 25 | }}} |