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;
}
}