Measuring Pulse Width

@ Rob

I have made few changes in the code and now the code is working fine :slight_smile: check it out but it only misses out 1 count I don't know how we can improve that? I mean for 1 microsecond pulse it is doing 15 counts (theoretically 16) can we give a external high clock to the timer of the arduino? The code is given below

#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint16_t cnt = 0;
unsigned int pulse_counts = 0;

void setup()
{
  Serial.begin(115200);
  Serial.println("PulseWidthMeter (timer1) 0.1");
  pinMode(3, INPUT);
}

void loop()
{
  // initialize Timer1
  cli();
  // reset counters
  cnt = 0;
  TCNT1 = 0;
  // reset registers
  TCCR1A = 0;
  TCCR1B = 0;

  pulse_counts++;
  // wait for HIGH
  while ((PIND & B00001000) == B00000000); 
  // Set CS10 bit so timer runs at clock speed: 16 MHz
  TCCR1B |= (1 << CS10);
  // enable Timer1 overflow interrupt:
  TIMSK1 = (1 << TOIE1);

  // enable global interrupts:
//  sei();

  // keep counting until LOW
  while ((PIND & B00001000) == B00001000); 
  // stop IRQ's


  TIMSK1 = 0;
  TCCR1B = 0;
 // cli();

    // Read the counters and convert to long
  uint16_t x = TCNT1;  // work copy
  uint32_t total = (uint32_t)cnt  + (uint32_t)x;
  float usec = (1.0 * total) / 16;

  // Display values
  Serial.print(x, DEC);
  Serial.print(" \t ");
  Serial.print(usec, 2);
  Serial.print(" \t ");
  Serial.print("Count = ");
  Serial.println(pulse_counts);

  // Wait a while
//  delay(1000);
}

// count the overflows in IRQ
ISR(TIMER1_OVF_vect)
{
  cnt++;
}