Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #define NUM_SAMPLES 10
  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 _duration;
  16.   unsigned long _pulseCount;
  17.   float Freq_Hz;
  18.   float Freq_RPM;
  19.  
  20.   // bufferize to avoid glitches
  21.   _duration = duration;
  22.   _pulseCount = pulseCount;
  23.  
  24.   if (_pulseCount == NUM_SAMPLES) {
  25.  
  26.     // clear counters
  27.     duration = 0;
  28.     pulseCount = 0;
  29.  
  30.     Freq_Hz = _pulseCount * 1e6 / float(_duration); // frequency in Hz
  31.     Freq_RPM = Freq_Hz * 60; // frequency in RPM
  32.  
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement