|
| 1 | +#include "CircuitsFunBasic.h" |
| 2 | +#if ARDUINO >= 100 |
| 3 | +#include "Arduino.h" |
| 4 | +#else |
| 5 | +#include "WProgram.h" |
| 6 | +#endif |
| 7 | + |
| 8 | +Button::Button(int pin,bool pressedValue){ |
| 9 | + this->pin=pin; |
| 10 | + this->pressedValue=pressedValue; |
| 11 | + this->debounceTime=0; |
| 12 | +} |
| 13 | +void Button::begin(){ |
| 14 | + //Must be called in setup |
| 15 | + pinMode(pin,INPUT); |
| 16 | +} |
| 17 | +bool Button::pressed(int timeout){ |
| 18 | + //from unpressed to pressed |
| 19 | + return checkPress(timeout,pressedValue); |
| 20 | +} |
| 21 | +bool Button::released(int timeout){ |
| 22 | + //from pressed to unpressed |
| 23 | + return checkPress(timeout,!pressedValue); |
| 24 | +} |
| 25 | +bool Button::doublePressed(int timeout,int tolerance){ |
| 26 | + //two clicks within tolerance time |
| 27 | + if(pressed(timeout)){ |
| 28 | + return pressed(tolerance); |
| 29 | + }else{ |
| 30 | + return false; |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +bool Button::isPressed(){ |
| 35 | + bool state=getState(); |
| 36 | + bool result=false; |
| 37 | + if(state!=lastState && state==HIGH){ |
| 38 | + result=true; |
| 39 | + } |
| 40 | + lastState=state; |
| 41 | + |
| 42 | + return result; |
| 43 | +} |
| 44 | + |
| 45 | + |
| 46 | +bool Button::checkPress(int timeout,bool requiredState){ |
| 47 | + //help function, check if the button has changed |
| 48 | + //from not "requiredState" to "requiredState" within timeout |
| 49 | + unsigned long timer=millis(); |
| 50 | + bool iStart=false; |
| 51 | + |
| 52 | + do{ |
| 53 | + if(!iStart){ |
| 54 | + if(getState()!=requiredState){ |
| 55 | + iStart=true; |
| 56 | + } |
| 57 | + }else{ |
| 58 | + if(getState()==requiredState){ |
| 59 | + delay(debounceTime); |
| 60 | + return true; |
| 61 | + } |
| 62 | + } |
| 63 | + //delay(10); |
| 64 | + }while(millis()-timer<=(unsigned long)timeout || timeout==0 ); |
| 65 | + |
| 66 | + return false; |
| 67 | +} |
| 68 | + |
| 69 | +bool Button::getState(){ |
| 70 | + return digitalRead(pin); |
| 71 | +} |
0 commit comments