comparison TiltSwitch.cpp @ 0:f2ccfa3f20ad default tip

more complete version from magic rattle
author ark
date 2017-06-28 00:48 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:f2ccfa3f20ad
1 #include "TiltSwitch.h"
2
3 /**
4 see TiltSwitch.h for description.
5 */
6
7 TiltSwitch::TiltSwitch() {}
8
9
10 void TiltSwitch::setup(byte pin, bool pu, float secs) {
11 this->pin = pin;
12 this->isPullup = pu;
13 this->dus = 1000000*secs;
14 pinMode(this->pin, this->isPullup?INPUT_PULLUP:INPUT);
15 this->isOn = this->readState();
16 this->act = 0.0;
17 }
18
19
20 void TiltSwitch::update(uint32_t us) {
21 bool s = this->readState();
22
23 // calculate rate of change per secs seconds
24 if(this->isOn != s) {
25 this->ref = this->act + 1.0;
26 this->refUs = us;
27 this->act = this->ref;
28 }
29 else {
30 uint32_t dt = (us - this->refUs);
31 if(dt >= this->dus) {
32 this->act = 0.0;
33 // guard against overflow
34 this->refUs = us - this->dus;
35 } else {
36 this->act = this->ref * ((float)(this->dus-dt)/(float)this->dus);
37 }
38 }
39 this->isOn = s;
40
41 // calculate average to determine up/down
42 // if collected MAX_SAMPLES already, simulate dropping a sample
43 if(this->num == MAX_SAMPLES) {
44 this->sum -= this->avg;
45 this->num--;
46 }
47 // add current sample
48 this->sum += (s ? 1.0 : 0.0);
49 this->num++;
50 this->avg = this->sum/this->num;
51 // if average is closer to 0 or 1 than 1/MAX_SAMPLES, meaning that it's
52 // less than one sample away from the stable bounds, truncate
53 if(this->num == MAX_SAMPLES) {
54 float e = 1/(float)MAX_SAMPLES-.001;
55 if(this->avg < e) {
56 this->avg = 0.0;
57 this->sum = 0.0;
58 }
59 else if(this->avg > 1.0-e) {
60 this->avg = 1.0;
61 this->sum = 1.0 * MAX_SAMPLES;
62 }
63 }
64 }
65
66
67 bool TiltSwitch::readState() {
68 bool s = digitalRead(this->pin);
69 if(this->isPullup) s = !s;
70 return s;
71 }
72