Arduino Playground is read-only starting December 31st, 2018. For more info please look at this Forum Post

YAButton Library:

Yet Another Button Library

There are many other Arduino Libraries out there that do button debouncing, but at the time of creating this library I could not find one that worked on an external polling system (so it can be run as a task) and handled button press callbacks. This library does both.

Features:

  • customizable active state: HIGH OR LOW (default is LOW to take advantage of the internal pull-up)
  • digital input is initialized when button is instantiated (set to INPUT if active state is HIGH, and INPUT_PULLUP if active state is low)
  • external control of the polling period (so it can be run as a periodic task)
  • register callback functions for button press, long press and release
  • customizable long press (wait for long press and repeated call while button is being held)

Usage:

First decide how often you want the button routine to run. This is your polling period (pollPeriod). Generally you want to poll the button fairly often so you detect the button press as quickly as possible. Try 10ms or 15ms.

Second you want to decide on a debounce period. Typical bounce time for a button is 10ms to 50ms, depending on the button. In the example I assume 30ms of debounce is required. Keep in mind that if your debounce time is set to longer than 50ms, you may find the buttons occasionally miss consecutive presses (because it is still debouncing the previous press). You may have to experiment a bit.
NOTE: The debounce period needs to be a multiple of the poll period (the button routine only runs on the polling period).

Third decide what you are going to do when the button is pressed, released and long pressed. This is done with callback functions. You register a callback function with the "set" methods. When that action occurs, the function will be called, to do whatever you want. The long press can either repeat the call or only call once.
NOTE: You only need to provide callback functions for the actions you want to handle.

  • For long press calls -- provide a callback, and provide a delay to wait (in milliseconds). If the longPressDelay is 0 then the long press callback will be called right after the (short) button press.
  • For continuous long press calls -- provide a callback, a longPressDelay and a repeatDelay. With the repeatDelay you can decide how often you want the long press function to be called. This is handy for things like setting the clock time or scrolling quickly though a list of options.
    NOTE: longPressDelay and repeatDelay should be multiples of the polling period.