aboutsummaryrefslogtreecommitdiff
path: root/arduino/Counter.cc
diff options
context:
space:
mode:
Diffstat (limited to 'arduino/Counter.cc')
-rwxr-xr-xarduino/Counter.cc98
1 files changed, 98 insertions, 0 deletions
diff --git a/arduino/Counter.cc b/arduino/Counter.cc
new file mode 100755
index 0000000..abf7c27
--- /dev/null
+++ b/arduino/Counter.cc
@@ -0,0 +1,98 @@
1#include "Counter.h"
2
3#include <Arduino.h>
4
5void Counter::init (unsigned long startDelay, unsigned long rpmCount, unsigned long signalsPerRPM)
6{
7 this->startDelay = startDelay;
8 this->rpmCount = rpmCount;
9 this->signalsPerRPM = signalsPerRPM;
10 reset();
11}
12
13void Counter::setStartDelay (unsigned long val)
14{
15 startDelay = val;
16}
17
18void Counter::setRPMCount (unsigned long val)
19{
20 rpmCount = val;
21}
22
23void Counter::setSignalsPerRPM (unsigned long val)
24{
25 signalsPerRPM = val;
26}
27
28void Counter::start (unsigned long startTime)
29{
30 if (state == READY)
31 {
32 this->startTime = startTime;
33 state = WAITING_FOR_TIMEOUT;
34 }
35}
36
37void Counter::reset ()
38{
39 state = READY;
40}
41
42void Counter::update (unsigned long t, int rpmSignal)
43{
44 switch (state)
45 {
46 case WAITING_FOR_TIMEOUT:
47 {
48 if (t - startTime >= startDelay)
49 {
50 startTime = t; // Update start time for counting state
51 signals = 0;
52 state = COUNTING;
53 }
54 break;
55 }
56 case COUNTING:
57 {
58 // Count signals in 1 second intervals
59 if (lastRpmSignal != rpmSignal && rpmSignal == HIGH)
60 {
61 signals++;
62 }
63 // 1 second interval reached
64 if (t - startTime >= 1000)
65 {
66 float rpm = ((float) signals / (float) signalsPerRPM) * 60.0f;
67 if (rpm <= rpmCount)
68 {
69 startTime = t; // Update start time for signaling state
70 state = SIGNALING;
71 }
72 else
73 {
74 // RPM threshold not reached.
75 // Count signals per second from scratch.
76 //Serial.print("rpm: \r\n"); Serial.print(rpm); Serial.print("\r\n");
77 startTime = t;
78 signals = 0;
79 }
80 }
81 break;
82 }
83 case SIGNALING:
84 {
85 if (t - startTime >= 3000)
86 {
87 state = READY;
88 }
89 }
90 default: break;
91 }
92 lastRpmSignal = rpmSignal;
93}
94
95Counter::State Counter::getState () const
96{
97 return state;
98}