Advertisement
TolentinoCotesta

PulseMeasure

Jul 3rd, 2017
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. // Duty cycle calculation using input capture unit
  2. // Author: Nick Gammon
  3. // Date: 5 November 2013
  4.  
  5. // Input: Pin D8
  6.  
  7. volatile boolean first;
  8. volatile boolean triggered;
  9. volatile unsigned long startTime, finishTime;
  10.  
  11. ISR (TIMER1_CAPT_vect) {
  12.    // wait until we noticed last one
  13.   if (triggered)
  14.     return;
  15.  
  16.   if (first) {
  17.     startTime = ICR1  ;    
  18.     TCCR1B =  bit (CS10);    // No prescaling, Input Capture Edge Select (falling on D8)
  19.     first = false;
  20.     return;  
  21.     }    
  22.    
  23.   finishTime = ICR1 ;
  24.   triggered = true;
  25. }
  26.  
  27. void prepareForInterrupts (){  
  28.   first = true;
  29.   triggered = false;   // re-arm for next time      
  30.   TCCR1B =  bit (CS10) | bit (ICES1);  // plus Input Capture Edge Select (rising on D8)
  31. }  
  32.  
  33. void setup () {
  34.   Serial.begin(115200);      
  35.   Serial.println("Pulse width measure");
  36.   TCCR1A = 0;
  37.   TCCR1B = 0;    
  38.   // Timer 1 - interrupt on  input capture,  no prescaler
  39.   TIMSK1 = bit (ICIE1);  
  40.   TCCR1B =  bit (CS10) | bit (ICES1);  // plus Input Capture Edge Select (rising on D8)
  41.   }
  42.  
  43. void loop ()
  44.   {
  45.   // wait till we have a reading
  46.   if (!triggered)
  47.     return;
  48.  
  49.   Serial.print ("Pulse took: ");
  50.   Serial.print (float (finishTime-startTime) * 62.5e-9 * 1e6);  // convert to microseconds
  51.   Serial.println (" uS. ");
  52.  
  53.   // Just for printing the value to serial monitor
  54.   delay (500);
  55.  
  56.   prepareForInterrupts ();  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement