I'm using Arduino mega 2560 and I need to measure time between changing output to 1 on one output and receiving RISING interrupt on other input pin.
So I read the current time just before setting the output to 1:
startTime = micros();
digitalWrite(output, 1);
And after that I'm waiting for interrupt where I get other time stamp by function micros() and compute time difference.
void change_0()
{
unsigned long currentTime = micros();
result = getTimeDifference(startTime, currentTime);
}
When I'm checking signals on oscilloscope (multiple signals), then I get time between signals on few measurements with max difference 3 microseconds(time spread). But in code I'm getting difference in time measurement 20 microseconds in multiple measurement. Absolute accuracy I can solve by calibration, but problem is with relative accuracy, because I'm getting different results on same input.
I know that Arduino is not best for this application, but is there any possibility how to get more accurate results? I need difference maximally 6 microseconds. What is the best accuracy I can get and how?
I tried TimerExtensions library, but with the same result.
Or should I use other variant of arduino or some special peripheral to achieve better accuracy?
Starting with that change_0 routine, is that run as part of an ISR? If so, I'd suggest doing this differently; only store the end time (micros()) and then do the calculus outside the ISR.
For more strict timing requirements, consider not relying on micros() at all but instead use one of the general purpose timers of your microcontroller. I'm not familiar with the 2560 specifically, but like any other micro, it'll have timers that can even be triggered from an external input without any software/code intervention, making the capture process extremely streamlined and accurate (within the boundaries of the controller's clock, which is likely not a problem).
In these two lines there are two issues, regarding to time measuring:
First - digitalWrite() itself will take 3.40 microseconds to execute on an Arduino Uno board. I can't obtain the time for the Mega, but it should be similar, I think.
Second - micros() can only be precise up to 4 microseconds.
To improve the precision one should use a direct port manipulation rather than digitalWrite() and count time by hardware timer instead of micros()