An Easy Arduino Software Debounce with code

Debouncing buttons can be a major issue for novice programmers, for something that seems so simple (Just put in a button!) it can be hours of pulling your hair out. Typically a button is partially debounced using hardware but what if you just want the ability to get rid of those false presses or stop it from thinking the button has been pressed 100 times in a second for a quick program? In any case I’ve got a basic way to debounce a button and then ignore the button for a set period of time. I’ll show the code and explain it as best I can below. Let me know if this helps you out! Also this code will show how I write most of my tinkering projects with a non blocking style and timed “routines”.

// Simple and Easy Software Button Debounce Code by Joshua David
// Techhelpblog.com
// 30/9/2013
//Define the BTN PIN
#define BTN 10

//Create a variable to store last routine run time in ms
unsigned long TIME50 = 0;

//Create some variables for the button
byte BTN_IGNORE = 0;
byte BTN_COUNT = 0;

void setup(){

  pinMode(BTN, INPUT);

}

void loop(){

  if(millis() - TIME50 >= 50){
    TIME50 = millis();
    //This if statement will run its contents every 50 Milliseconds. No main loop delays!

    CHECK_BUTTONS();

  }

 //Rest of the program

}

void CHECK_BUTTONS(void){

  if(BTN_IGNORE == 0){      //Anything above 0 means we are ignoring the buttons
  //Next line will increment the BTN_COUNT every 50 ms while it is less than 4 and the BTN is HIGH
    if((digitalRead(BTN)) && (BTN_COUNT <= 3)) BTN_COUNT++;

  //Next line will see if the BTN is HIGH and if the 200ms of debounce has been met
    if((digitalRead(BTN)) && (BTN_COUNT >= 4)){
      //BTN PRESS ACTIONS GO HERE

      BTN_COUNT = 0;  //Reset the button counter
      BTN_IGNORE = 20;  //Set a 1 Second Ignore counter
    }

  //Next line will reset counters if the button press was a bounce
    if((digitalRead(BTN) == false) && (BTN_COUNT > 0)) BTN_COUNT = 0;
  }

  //Count Down the Button Ignore variable
  if(BTN_IGNORE >= 1) BTN_IGNORE = BTN_IGNORE - 1;

}

As many of you know there is so many ways this could be written or modified or even sped up a bit. You’ll notice I didn’t use the else statement from the first if in the button check routine plus many other ways this could be streamlined a bit more. But for the general use this is a neat functional way to make buttons behave the way most users would expect them to. And if you follow the timed routine style coding you will typically pickup the button presses more accurately! Remember this is not using an interrupt so it needs to run in a fairly fast program. Questions in the comments.

Share

Tags: , , , , , , , ,

No comments yet.

Leave a Reply