|
0
|
1 #if defined(ARDUINO) && ARDUINO >= 100
|
|
|
2 #include "Arduino.h"
|
|
|
3 #else
|
|
|
4 #include "WProgram.h"
|
|
|
5 #endif
|
|
|
6
|
|
|
7 #include "Button.h"
|
|
|
8
|
|
|
9 /**
|
|
|
10 see Button.h for description.
|
|
|
11 */
|
|
|
12
|
|
|
13 Button::Button() {}
|
|
|
14
|
|
|
15 void Button::setup(byte pin) {
|
|
|
16 this->setup(pin, true);
|
|
|
17 }
|
|
|
18
|
|
|
19 void Button::setup(byte pin, bool pu) {
|
|
|
20 this->pin = pin;
|
|
|
21 this->isPullup = pu;
|
|
|
22 pinMode(this->pin, this->isPullup?INPUT_PULLUP:INPUT);
|
|
1
|
23 this->isOn = this->readState();
|
|
0
|
24 this->lastChangeMs = 0;
|
|
|
25 }
|
|
|
26
|
|
|
27 void Button::update() {
|
|
|
28 this->update(millis());
|
|
|
29 }
|
|
|
30
|
|
|
31
|
|
|
32 void Button::update(unsigned long ms) {
|
|
|
33 bool s = this->readState();
|
|
|
34 // process state change
|
|
1
|
35 if(this->isOn != s) {
|
|
0
|
36 // if last state change is older than threshold, accept new state
|
|
|
37 // change is not a bounce.
|
|
|
38 if(ms - this->lastChangeMs >= Button::BOUNCE_THRESHOLD) {
|
|
1
|
39 this->isPressed = this->isOn;
|
|
|
40 this->isReleased = !this->isOn;
|
|
|
41 this->isOn = s;
|
|
0
|
42 this->lastChangeMs = ms;
|
|
|
43 }
|
|
1
|
44 } else {
|
|
|
45 this->isPressed = false;
|
|
|
46 this->isReleased = false;
|
|
0
|
47 }
|
|
|
48 }
|
|
|
49
|
|
|
50
|
|
|
51 bool Button::readState() {
|
|
|
52 bool s = digitalRead(this->pin);
|
|
|
53 if(this->isPullup) s = !s;
|
|
|
54 return s;
|
|
|
55 }
|
|
|
56
|