|
// This example code is based on http://www.arduino.cc/en/Tutorial/Debounce |
|
|
|
boolean debug = true; |
|
long debounceDelay = 50; |
|
|
|
class LEDButton{ |
|
public: |
|
int buttonPin = 0; |
|
int buttonState = 0; |
|
int lastButtonState = LOW; |
|
int ledPin = 0; |
|
int ledState = HIGH; |
|
long lastDebounceTime = 0; |
|
|
|
void CheckPush(){ |
|
int reading = digitalRead(this->buttonPin); |
|
|
|
if (reading != this->lastButtonState) { |
|
this->lastDebounceTime = millis(); |
|
} |
|
|
|
if ((millis() - this->lastDebounceTime) > debounceDelay) { |
|
// whatever the reading is at, it's been there for longer |
|
// than the debounce delay, so take it as the actual current state: |
|
|
|
// if the button state has changed: |
|
if (this->buttonState != reading) { |
|
|
|
if (debug && this->buttonPin == A5){ |
|
Serial.println("reading"); |
|
Serial.println(reading); |
|
} |
|
|
|
this->buttonState = reading; |
|
|
|
// only toggle the LED if the new button state is HIGH |
|
if (this->buttonState == HIGH) { |
|
ChangeLEDState(!this->ledState); |
|
} |
|
} |
|
} |
|
|
|
this->lastButtonState = reading; |
|
} |
|
|
|
void Init(){ |
|
pinMode(this->buttonPin, INPUT); |
|
pinMode(this->ledPin, OUTPUT); |
|
|
|
digitalWrite(this->ledPin, this->ledState); |
|
} |
|
|
|
private: |
|
|
|
void ChangeLEDState(int newState){ |
|
digitalWrite(this->ledPin, newState); |
|
this->ledState = newState; |
|
} |
|
|
|
|
|
}; |
|
|
|
|
|
LEDButton* b1; |
|
LEDButton* b2; |
|
LEDButton* b3; |
|
LEDButton* b4; |
|
|
|
LEDButton* createButton(int buttonPin, int buttonState, int lastButtonState, int ledPin, int ledState){ |
|
LEDButton* b = new LEDButton(); |
|
b->buttonPin = buttonPin; |
|
b->buttonState = buttonState; |
|
b->lastButtonState = lastButtonState; |
|
b->ledPin = ledPin; |
|
b->ledState = ledState; |
|
return b; |
|
} |
|
|
|
void setupButtons(){ |
|
b1 = createButton(9, 0, LOW, 13, HIGH); |
|
b2 = createButton(8, 0, LOW, 12, HIGH); |
|
b3 = createButton(A5, 0, LOW, 11, HIGH); |
|
b4 = createButton(A5, 0, HIGH, 10, LOW); |
|
|
|
b1->Init(); |
|
b2->Init(); |
|
b3->Init(); |
|
b4->Init(); |
|
} |
|
|
|
void setup() { |
|
if (debug){ |
|
Serial.begin(9600); |
|
} |
|
|
|
setupButtons(); |
|
} |
|
|
|
void loop() { |
|
b1->CheckPush(); |
|
b2->CheckPush(); |
|
b3->CheckPush(); |
|
b4->CheckPush(); |
|
} |