Sunday, 30 June 2013

Button Debouncing Library for Arduino

I decided to write a small library to handle polling and debouncing of a button for the Arduino. The library is really simple, and uses a timer interrupt to do the polling and debouncing, much the same as my IR decoder and rotary encoder libraries. This allows it to run in the background, without affecting your main sketch, a bit like the millis() function does.

The library can be downloaded here:

Here is the example sketch:

#include "Debounce.h"

const int buttonPin = 10;

int buttonState = 0;
int buttonStateOld = 0;

int ledState = 0;

void setup()
  pinMode(13, OUTPUT);
  debounce_begin(buttonPin); // State debouncing a button on buttonPin

void loop()
  buttonState = button_data(); // Check button state
  // Toggle pin 13 LED if the button's been pressed
  if(buttonState != buttonStateOld)
    buttonStateOld = buttonState;
    if(buttonState == 1)
      ledState = !ledState;
      digitalWrite(13, ledState);

The debounce_begin() function sets up the library and the input pin you enter, and button_data() returns the debounced state of the button.

Debouncing is done using a state machine with three states, standby, waiting, and delaying.
  • In the standby state, it reads in the value of the button pin, then moves on to the waiting state.
  • In the waiting state, it keeps checking the button pin, waiting for a change. If it sees one (ie. the button was pressed/released) it moves on to the delaying state.
  • When its in the delaying state, it just delays for a period of time set by DEBOUNCE_DELAY using a counter. When the time is up, it reads the value of the button pin into the data variable, which is now the debounced state of the button. It then goes back to the standby state.

The debounce delay can be set in the Debounce.h file by changing DEBOUNCE_DELAY. It is measured in multiples of 300 us, which the time between each interrupt. The default debounce delay is approximately 20 ms, but some experimentation may be needed to find a reliable time.

The library can only handle one button at the moment, but I hope to add support for multiple buttons in the future.

Just one more thing: the library configures timer2 in a way which might conflict with the Tone library, and also may cause problems when trying to use pwm on digital pins 9 and 10.

No comments:

Post a Comment