Advertisement
Guest User

Rpm

a guest
Aug 24th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. volatile boolean first;
  2. volatile boolean triggered;
  3. volatile unsigned long overflowCount;
  4. volatile unsigned long startTime;
  5. volatile unsigned long finishTime;
  6.  
  7. // here on rising edge
  8. void isr ()
  9. {
  10. unsigned int counter = TCNT1; // quickly save it
  11.  
  12. // wait until we noticed last one
  13. if (triggered)
  14. return;
  15.  
  16. if (first)
  17. {
  18. startTime = (overflowCount << 16) + counter;
  19. first = false;
  20. return;
  21. }
  22.  
  23. finishTime = (overflowCount << 16) + counter;
  24. triggered = true;
  25. detachInterrupt(0);
  26. } // end of isr
  27.  
  28. // timer overflows (every 65536 counts)
  29. ISR (TIMER1_OVF_vect)
  30. {
  31. overflowCount++;
  32. } // end of TIMER1_OVF_vect
  33.  
  34.  
  35. void prepareForInterrupts ()
  36. {
  37. // get ready for next time
  38. EIFR = _BV (INTF0); // clear flag for interrupt 0
  39. first = true;
  40. triggered = false; // re-arm for next time
  41. attachInterrupt(0, isr, RISING);
  42. } // end of prepareForInterrupts
  43.  
  44.  
  45. void setup () {
  46. Serial.begin(115200);
  47. Serial.println("Frequency Counter");
  48.  
  49. // reset Timer 1
  50. TCCR1A = 0;
  51. TCCR1B = 0;
  52. // Timer 1 - interrupt on overflow
  53. TIMSK1 = _BV (TOIE1); // enable Timer1 Interrupt
  54. // zero it
  55. TCNT1 = 0;
  56. // start Timer 1
  57. TCCR1B = _BV (CS20); // no prescaling
  58.  
  59. // set up for interrupts
  60. prepareForInterrupts ();
  61.  
  62. } // end of setup
  63.  
  64. void loop ()
  65. {
  66.  
  67. if (!triggered)
  68. return;
  69.  
  70. unsigned long elapsedTime = finishTime - startTime;
  71. float freq = 1.0 / ((float (elapsedTime) * 62.5e-9)); // each tick is 62.5 nS
  72.  
  73. Serial.print ("Took: ");
  74. Serial.print (elapsedTime);
  75. Serial.print (" counts. ");
  76.  
  77. Serial.print ("Frequency: ");
  78. Serial.print (freq);
  79. Serial.println (" Hz. ");
  80.  
  81. Serial.print ("RPM: ");
  82. Serial.print (freq*60.0);
  83. Serial.println (" rpm. ");
  84.  
  85. // so we can read it
  86. delay (500);
  87.  
  88. prepareForInterrupts ();
  89. } // end of loop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement