// c l a s s S w i t c h M a n a g e r W i t h F i l t e r
//********************************************^************************************************
/*
Class for making "switch" objects
Noise filter Added REV. 1.01 LarryD
inspired by Nick Gammon's "class" below:
http://gammon.com.au/Arduino/SwitchManager.zip
Example:
//if used from an external library
#include <SwitchManagerWithFilter.h>
//"switch" object instantiations
SwitchManagerWithFilter mySwitch;
void setup()
{
//create a "switch" object
mySwitch.begin (2, handleSwitches);
}
void loop()
{
mySwitch.check(); //check for "switch" operation, do this at loop() speed
}
//When a valid "switch" operation is detected:
//- newState will be LOW or HIGH (the state the "switch" is now in)
//- interval will be how many mS between the opposite state and this state
//- whichPin will be the pin that caused this change
//you can share the function amongst multiple switches
void handleSwitches(const byte newState, const unsigned long interval, const byte whichPin)
{
//do something
}
*/
class SwitchManagerWithFilter
{
enum {debounceTime = 13, noSwitch = -1};
typedef void (*handlerFunction)
(
const byte newState,
const unsigned long interval,
const byte whichSwitch
);
int pinNumber_;
handlerFunction f_;
byte oldSwitchState_;
unsigned long switchPressTime_; //when the "switch" last changed state
unsigned long lastLowTime_;
unsigned long lastHighTime_;
byte sampleCounter_;
public:
//constructor
SwitchManagerWithFilter()
{
pinNumber_ = noSwitch;
f_ = NULL;
oldSwitchState_ = 0;
switchPressTime_ = 0;
lastLowTime_ = 0;
lastHighTime_ = 0;
sampleCounter_ = 0;
}
//****************************************
void begin (const int pinNumber, handlerFunction f)
{
pinNumber_ = pinNumber;
f_ = f;
//*********************
if (pinNumber_ != noSwitch)
{
pinMode (pinNumber_, INPUT_PULLUP);
oldSwitchState_ = digitalRead(pinNumber_);
}
}
void check()
{
if (pinNumber_ == noSwitch || f_ == NULL)
return;
unsigned long commonTime = millis();
if (commonTime - switchPressTime_ < debounceTime)
return;
byte switchState = digitalRead(pinNumber_);
if (switchState != oldSwitchState_) {
if (switchState == LOW) {
lastLowTime_ = commonTime;
f_ (LOW, lastLowTime_ - lastHighTime_, pinNumber_);
}
else {
lastHighTime_ = commonTime;
f_ (HIGH, lastHighTime_ - lastLowTime_, pinNumber_);
}
oldSwitchState_ = switchState;
switchPressTime_ = commonTime;
}
}
}; //END of class SwitchManagerWithFilter
SwitchManagerWithFilter mySwitch;
void setup()
{
Serial.begin(115200);
Serial.println("hello world!");
mySwitch.begin (2, handleSwitches);
}
void loop()
{
mySwitch.check(); //check for "switch" operation, do this at loop() speed
}
void handleSwitches(const byte newState, const unsigned long interval, const byte whichPin)
{
Serial.print(newState ? " UP after " : "DOWN after ");
Serial.println(interval);
}