Why is there ±2 cycles of jitter for interrupt timing measurements?

I'm trying to determine the maximum stability that can be achieved when using an external interrupt and timer2 on an UNO to measure the period of a high frequency signal. The signal is generated by an Arduino Due (100kHz, 4µs high, 6µs low).

After accumulating 1000 readings, the best stability I can achieve at this rate is ±2 cycles from the median value. I'm expecting a count of 160 and after correcting for 8 cycles offset, getting 157 to 161.

I know the signal is clean and is compatible with the UNO ... scope trace looks good and verifying on pin8 (capture unit) with FreqMeasure library gives stable readings of 160.

Is ±2 cycles jitter normal?
Can it somehow be improved or is it created by IDE itself or have I just hit the limit of the hardware?

Here's the test code:

const byte inputPinA = 2;
volatile byte flagA = 0, periodA = 0;
byte dataA[1000], minA, maxA;
word readCount;

void setup()
{
  Serial.begin(115200);
  pinMode(inputPinA, INPUT_PULLUP);
  pinMode (LED_BUILTIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(inputPinA), inputA_ISR, FALLING);

  for (int i = 0; i < 1000; i++) {
    dataA[i] = 0;
  }

  EIMSK &= ~bit(INT0);     // disable INT0 interrupt
  EIFR |= bit(INTF0);      // clear INT0 interrupt flag
  TCCR2A = 0;              // normal operation mode
  TCCR2B = 0;              // stop timer clock (no clock source)
  TCNT2  = 0;              // clear counter

  TIMSK0 = 0;              // for testing with timer0 disabled
  readCount = 0;
  minA = 255;
}

void loop()
{
  if ((flagA == 2) && (readCount < 1000)) {
    noInterrupts();
    dataA[readCount] = TCNT2;
    readCount++;
    flagA = 0;
    TCNT2  = 0;            // clear counter
    EIFR = bit(INTF0);     // clear INT0 interrupt flag
    EIMSK |= bit(INT0);    // enable INT0 interrupt
    interrupts();
  }
  if (readCount == 1000) {
    for (int i = 0; i < 1000; i++) {
      Serial.println(dataA[i]);
      if (i) {
        minA = (dataA[i] < minA) ? dataA[i] : minA;
        maxA = (dataA[i] > maxA) ? dataA[i] : maxA;
      }
    }
    Serial.print("minA  ");
    Serial.println(minA);
    Serial.print("maxA  ");
    Serial.println(maxA);
    noInterrupts();
    readCount = 5555; // stop testing and printing
    interrupts();
  }
}

void inputA_ISR()
{
  if (flagA == 1) {
    __builtin_avr_delay_cycles (8); // temporary offset
    TCCR2B = 0;              // stop timer clock (no clock source)
    periodA = TCNT2;

    EIMSK &= ~bit(INT0);     // disable INT0 interrupt
    EIFR = bit(INTF0);       // clear INT0 interrupt flag
    flagA = 2;

  } else if (flagA == 0) {
    TCCR2B |= bit(CS20);     // start timer clock (62.5ns period)
    flagA = 1;
  }
}

Further research:

Looking at the Atmel AVR 8-bit Instruction Set, I can see cycles per instruction can be from 1-4, depending upon the instruction or condition.

Looking through Nick Gammon's Interrupts link (once more), it states

Executing the next instruction after enabling interrupts: "In all cases, the processor guarantees that the next instruction after interrupts are enabled (if they were previously disabled) will always be executed, even if an interrupt event is pending. (By "next" I mean the next one in program sequence, not necessarily the one physically following. For example, a RETI instruction jumps back to where the interrupt occurred, and then executes one more instruction)."

From this, it would seem the ± 2 cycles of interrupt latency jitter is normal.

If you measure the period using one of the 16 bit counters then you can use the ICPn input. This records the count in the ICRn register at the point the edge triggers the interrupt so you don't have to worry about interrupt latency. You only have to make sure you can handle one interrupt before the next one arrives.

Using this approach you can expect an average error of about sqrt(2) clock cycles.

Two clocks is about as good as you'll get on any micro-controller. External inputs must be synchronized to the device clock before they can be recognized. Failure to do this will lead to erroneous results, due to meta-stability in flip-flops if setup/hold times are not met. A typical digital input will be passed through two flip-flops before being even looked at by the MCUs logic, as detailed in the Atmel datasheets. These flip-flops are clocked by ClkIO. You'd have to look at the actual configuration settings used in setting up the chip to figure out what the ClkIO frequency actually is, but your minimum time to recognize any chance in an input state will be two full cycles of ClkIO.

The FAR more accruate way to measure period of an external signal is to setup a timer in capture mode to do the measurement entirely in hardware, rather than using interrupts (which can be delayed significantly by other interrupts, like the millis() timer or Serial ports).

Regards,
Ray L.

Thank you for your replies. I'm familiar with the input capture unit and how it's linked to timer1, however if these resources are unavailable, it would be good to have an alternative approach.

I will be investigating using timer2, INT0 and INT1 for accurate time interval measurements between the same edge of two different signals. I have a new test sequence (untested) that should avoid pending interrupts from affecting the test results and my goal is to achieve ±1 cycle resolution (±62.5ns) after a little bit of averaging. If the 2 inputs are at 60Hz, this would be 0.00135º phase resolution.

A typical digital input will be passed through two flip-flops before being even looked at by the MCUs logic, as detailed in the Atmel datasheets.

Thanks RayLivingston, I've overlooked this. +1