View difference between Paste ID: U2NWQacd and sVWKjEYP
SHOW: | | - or go back to the newest paste.
1-
#define MainPeriod 100
1+
#define NUM_SAMPLES 10
2-
long previousMillis = 0;
2+
3
volatile unsigned long duration = 0;
4
volatile unsigned int pulseCount = 0;
5
volatile unsigned long previousMicros = 0;
6
7
8
void setup() {
9
  Serial.begin(19200);
10
  attachInterrupt(digitalPinToInterrupt(2), myIntHandler, RISING);
11
}
12
13
14
void loop() {
15-
  unsigned long currentMillis = millis();
15+
  unsigned long _duration;
16
  unsigned long _pulseCount;
17-
  if (currentMillis - previousMillis >= MainPeriod) {
17+
  float Freq_Hz;
18-
    // bufferize to avoid glitches
18+
  float Freq_RPM;
19-
    unsigned long _duration = duration;
19+
 
20-
    unsigned long _pulseCount = pulseCount;
20+
  // bufferize to avoid glitches
21
  _duration = duration;
22
  _pulseCount = pulseCount;
23
24
  if (_pulseCount == NUM_SAMPLES) {
25
26-
    float Freq = 1e6 / float(_duration);
26+
27-
    Freq *= 60;
27+
28-
    Freq *= _pulseCount;
28+
29
30-
    if (!(isnan(Freq))) {
30+
    Freq_Hz = _pulseCount * 1e6 / float(_duration); // frequency in Hz
31-
      Serial.print("freq: ");
31+
    Freq_RPM = Freq_Hz * 60; // frequency in RPM
32-
      Serial.println(Freq);
32+
33-
    }
33+
    Serial.print("freq: ");
34
    Serial.println(Freq_RPM);
35
  }
36
}
37
38
39
void myIntHandler() {
40
  unsigned long currentMicros = micros();
41
  
42
  duration += currentMicros - previousMicros;
43
  previousMicros = currentMicros;
44
  pulseCount++;
45
}