|
0
|
1 #include "Arduino.h"
|
|
|
2 #include "Potentiometer.h"
|
|
|
3
|
|
|
4 /**
|
|
|
5 see Potentiometer.h for description.
|
|
|
6 */
|
|
|
7
|
|
|
8 Potentiometer::Potentiometer() {}
|
|
|
9
|
|
|
10 void Potentiometer::setup(byte pin) {
|
|
|
11 this->pin = pin;
|
|
|
12 pinMode(this->pin, INPUT);
|
|
5
|
13 this->isStopped = false;
|
|
|
14 this->sum = 0.0;
|
|
|
15 this->avg = 0.0;
|
|
|
16 this->num = 0;
|
|
0
|
17 }
|
|
|
18
|
|
|
19 void Potentiometer::update() {
|
|
|
20 int v = analogRead(this->pin);
|
|
|
21 // if value is within jitter threshold of current value, add to average
|
|
6
|
22 int diff = abs(this->value - v);
|
|
|
23 if(this->num == 0 || diff <= Potentiometer::JITTER_THRESHOLD) {
|
|
0
|
24 if(this->num == Potentiometer::MAX_SAMPLES) {
|
|
|
25 this->sum -= this->avg;
|
|
|
26 this->num--;
|
|
1
|
27 this->isStopped = true;
|
|
0
|
28 }
|
|
|
29 this->sum += v;
|
|
|
30 this->num++;
|
|
|
31 this->avg = this->sum/this->num;
|
|
|
32 this->value = (int)(this->avg+.5);
|
|
6
|
33 this->ignore = false;
|
|
0
|
34 }
|
|
6
|
35 // otherwise
|
|
0
|
36 else {
|
|
6
|
37 // ignore one value above jitter
|
|
|
38 if(!this->ignore) {
|
|
|
39 this->ignore = true;
|
|
|
40 }
|
|
|
41 // otherwise, if already ignored one spike, reset average
|
|
|
42 else {
|
|
|
43 this->value = v;
|
|
|
44 this->sum = v;
|
|
|
45 this->avg = v;
|
|
|
46 this->num = 1;
|
|
|
47 this->isStopped = false;
|
|
|
48 this->ignore = false;
|
|
|
49 }
|
|
0
|
50 }
|
|
|
51 #ifdef DEBUG
|
|
|
52 Serial.print("pin=");
|
|
|
53 Serial.print(pin);
|
|
|
54 Serial.print(", sum=");
|
|
|
55 Serial.print(sum);
|
|
|
56 Serial.print(", num=");
|
|
|
57 Serial.print(num);
|
|
|
58 Serial.print(", avg=");
|
|
2
|
59 Serial.print(avg);
|
|
|
60 Serial.print(", v=");
|
|
6
|
61 Serial.print(v);
|
|
|
62 Serial.print(", diff=");
|
|
|
63 Serial.print(diff);
|
|
|
64 Serial.print(", ignore=");
|
|
|
65 Serial.print(ignore);
|
|
1
|
66 Serial.print(", isStopped=");
|
|
6
|
67 Serial.print(this->isStopped);
|
|
|
68 Serial.println("");
|
|
0
|
69 #endif
|
|
|
70 }
|
|
|
71
|
|
|
72
|
|
|
73 void Potentiometer::update(unsigned long ms) {
|
|
|
74 this->update();
|
|
|
75 }
|
|
|
76
|
|
|
77
|
|
|
78
|