-
Notifications
You must be signed in to change notification settings - Fork 4
/
pinTime.ino
90 lines (77 loc) · 2.05 KB
/
pinTime.ino
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
void initPinTimer(pinTime &pin, int pin_number, size_t readings) {
if(readings > 512)
readings = 512;
pin.bufferSize = readings;
pin.pin = pin_number;
// init valueBuffer to value 0
for(size_t i; i<readings; i++) {
pin.valueBuffer[i] = 0;
}
}
/*
* pin is pin number
* timout is when the pin is either high or low for sure
* readings is the number of readings to average
*/
void calcPinTime(pinTime &pin, unsigned int timeout) {
unsigned long now = millis();
pin.changed = false;
pin.statusChanged = false;
int value = digitalRead(pin.pin); //calculateAverageValue(pin);
if(value != pin.lastValue or pin.lastValue == -1) {
pin.changed = true;
if(value == LOW) {
pin.lastValue = LOW;
pin.high = now - pin.lastPinLow;
}
else {
pin.lastValue = HIGH;
pin.low = now - pin.lastPinHigh;
}
}
if(value == LOW) {
pin.lastPinLow = now;
}
else {
pin.lastPinHigh = now;
}
unsigned long highTime = now - pin.lastPinLow;
unsigned long lowTime = now - pin.lastPinHigh;
//determine pin state (on, off or blinking)
if(highTime > timeout) {
if(pin.isHigh != true)
pin.statusChanged = true;
pin.isHigh = true;
pin.isLow = false;
pin.isBlinking = false;
pin.ratio = 1;
}
else if(lowTime > timeout) {
if(pin.isLow != true)
pin.statusChanged = true;
pin.isLow = true;
pin.isHigh = false;
pin.isBlinking = false;
pin.ratio = 0;
}
else { //is blinking
if(pin.isBlinking != true)
pin.statusChanged = true;
pin.isHigh = false;
pin.isLow = false;
pin.isBlinking = true;
pin.ratio = (float)pin.high/(float)(pin.low+pin.high);
}
}
int calculateAverageValue(pinTime &pin) {
//first add reading to buffer
pin.valueBuffer[pin.valn] = digitalRead(pin.pin);
pin.valn++;
if(pin.valn == pin.bufferSize)
pin.valn = 0;
unsigned int sum = 0;
for(size_t i = 0; i < pin.bufferSize; i++) {
sum += pin.valueBuffer[i];
}
return sum > (int)pin.bufferSize*0.9; //70 percent is positive, count as positive;
}