comparison Button.cpp @ 0:968a3e3eb8ef

initial - v1.0
author ark
date 2017-01-22 23:39 +0100
parents
children 284066a427c8
comparison
equal deleted inserted replaced
-1:000000000000 0:968a3e3eb8ef
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);
23 this->isPressed = this->readState();
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
35 if(this->isPressed != s) {
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) {
39 this->isPressed = s;
40 this->lastChangeMs = ms;
41 }
42 else {
43 Serial.print("ignoring bounce at ");
44 Serial.println(ms);
45 }
46 }
47 }
48
49
50 bool Button::readState() {
51 bool s = digitalRead(this->pin);
52 if(this->isPullup) s = !s;
53 return s;
54 }
55