Arduino: debounce buttons - how it works
To properly debounce a button on your Arduino, you only need a few lines of code. In this practical tip, we will explain to you exactly what these are.
Debounce buttons on the Arduino
If you connect a button to the Arduino and press it, the Arduino may register the button press as multiple presses. This phenomenon is called "bouncing". However, a button to "debounce" is very simple.
- To do this, first write "if (digitalRead (4)) {" to check whether the button on pin 4 has been switched to "HIGH", that is, has been pressed.
- Then let the Arduino wait 5 milliseconds: "delay (5);".
- Then insert the if statement again. Then you can insert the actual commands. Now the commands are only executed if the button has been pressed correctly.
Arduino: code example for push button debouncing
- void setup () {
- pinMode (4, INPUT_PULLUP);
- }
- void loop () {
- if (digitalRead (4)) {
- delay (5);
- if (digitalRead (4)) {
- // ...
- }
- }
- }
In the next practical tip we will explain how to send an SMS with the Arduino.