enum { ButNone, ButDown, ButStill, ButShort, ButLong };
# define DEBOUNCE 100 // absurd to demonstrate use 50 or wahtever you get away with
struct Button {
const unsigned long MsecShort = 1000;
byte _pin;
byte _state = HIGH;
unsigned long _msec;
public:
Button (int pin) {
_pin = pin;
pinMode (_pin, INPUT_PULLUP);
_state = digitalRead (_pin);
}
int read (void) {
unsigned long now = millis();
if (now - _msec < DEBOUNCE) {
if (_state == LOW)
return (ButStill);
else
return (ButNone);
}
// we can look at the button again
byte but = digitalRead (_pin);
byte returnValue;
if (_state != but) {
_state = but;
// delay (10); // debounce
if (LOW == but) {
returnValue = ButDown;
}
else
returnValue = (now - _msec > 1000) ? ButLong : ButShort;
_msec = now;
}
else returnValue = (_state == LOW) ? ButStill : ButNone;
return returnValue;
}
};
Button but (A1);
// -----------------------------------------------------------------------------
void loop()
{
static byte printedStill = false;
switch (but.read ()) {
case ButDown :
Serial.println("button pressed");
break;
case ButStill :
if (!printedStill) {
Serial.println(" and is being held");
printedStill = true;
}
break;
case ButShort:
Serial.println ("short");
printedStill = false;
break;
case ButLong:
Serial.println ("long");
printedStill = false;
break;
}
}
void setup()
{
Serial.begin (9600);
Serial.println("Hello ButtonThingWorld!\n");
}