-
Notifications
You must be signed in to change notification settings - Fork 30
/
CV.cpp
63 lines (47 loc) · 1.13 KB
/
CV.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#ifndef CV_h
#define CV_h
#include "Arduino.h"
class CV {
public:
/**
* Setup the analog input reader (CV input or knob), specifying optional thresholds
*/
void init(byte pin, int thresholdLow = 0, int thresholdHigh = 1023, bool invert = false) {
this->pin = pin;
this->thresholdLow = thresholdLow;
this->thresholdHigh = thresholdHigh;
this->invert = invert;
}
/**
* Return the raw reading, as returned by analogRead()
*/
int readRaw() {
return analogRead(this->pin);
}
/**
* Return the reading as a float number between 0 and 1, included.
* Optional thresholds are used to map the raw values into the returned 0..1 range.
*/
float read() {
int r = this->readRaw();
float f;
if (r <= this->thresholdLow) {
f = 0.0;
} else if (r >= this->thresholdHigh) {
f = 1.0;
} else {
f = float(r - this->thresholdLow) / float(this->thresholdHigh - this->thresholdLow);
}
if (this->invert) {
return 1.0 - f;
} else {
return f;
}
}
private:
byte pin;
int thresholdLow;
int thresholdHigh;
bool invert;
};
#endif