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

Buttons

Buttons is a small library to use hardware-debounced switches. Have you ever noticed that when you press a button, digitalRead will send you the information that the button is pressed everytime you call it? Just imagine you want to count the number of times the button has been pressed, with a counter: it will increment each time the function digitalRead is called, about 50 times/second.

This library allow you to use a button (digital input) that will send some information related to its mode and its state.

There are 5 button modes:

  • OneShot: OneShot only, returns 2 values (ON/OFF)
  • Memory: Returns (Pressed/ON/Released/OFF)
  • Timer: Hold System (OFF/ON/Hold)
  • OneShotTimer: Combi OneShot & Timer (ON/Hold/OFF)
  • MemoryTimer: Combi Memory & Timer (Pressed/ON/Hold/Released/OFF)

Download the library [zip archive - 64.4kb] Last update: 29/03/09

How to use it:

There are 2 ways to instance the library, the classic one that makes a default button (you can change the mode and parameters later), and the constructor with mode assignment.

Don't forget to link the Arduino pins to the library with ButtonName.assign...

You can set the mode of your button (among the availble modes described above), whenever you want (yep, you can change it in the middle of a sketch).

ButtonName.setTimer is only available for Timer-based modes. It sets the level for which the ButtonName.check returns Hold. This is not a milisecond value, it's the number of times you need to call the ButtonName.check function in an (almost) infinite loop.

You can even change the mode temporarily, with ButtonName.check(mode), it applies the mode you give it just for this call of the check function, then sets it back to its original value.

About time...

29/03/09 Update brings the "almost realtime" behavior to your buttons. It's now time-driven, it does not wait for something to happen anymore, you can use a full speed loop for calling check(), it won't slow your program as it did before. As a counterpart, you may experience some troubles using this library with interrupts..



I was able to compile past the WProgram.h error by changing the offending line in the mentioned headr file to this include instead:

#if defined(ARDUINO) && ARDUINO >= 100
      #include "Arduino.h"
#else
      #include "WProgram.h"
#endif