Im not sure if I posted to the right forum but i think my question is hardware and software related so i came here.
Im doing some tests with the 'millis()' function and have the question:
millis will really measure the time with accuracy (a despite of the crystal accuracy), and not consider the proccessing time until code reaches 'millis()' function?
To be more clear, im using this testing sketch:
<<
unsigned long time;
long counter = 0 ;
void setup(){
Serial.begin(19200);
}
void loop(){
time = millis();
delay(1000);
Serial.println(time);
// ================================ //
// ==== Lots of Code here ========== //
// ================================ //
}
From the serial monitor i got the results: { 0, 1001, 2004, 3007, 4011, 5014 } and i got the exact same results in two Arduinos Severino, using different brands of crystals.
At first I expected sinchronized results like {0, 1000, 2000, ... }.
The difference between the seconds measures are the time Arduino late to proccess the code until reaches 'millis()'? Despite of anything, 'millis()' will show me the real time or it lags depending of how much code are we processing?
delay(); will delay at least the amount of ms speciefied by the argument.
You are not guaranteed a delay of precisely the requested amount.
[edit]Of cource, the code between the millis(); calls will have an impact on the frequency of the calls, but won't impact the millis(); call itself.
And when I think of it, I am uncertain of my previous statement. Maybe you are guaranteed a millisecond resolution, but not, if I remember correctly microsecond resolution.[/edit]
millis() should be pretty accurate. delay() is NOT very accurate.
time = millis();
delay(1000);
Serial.println(millis() - time);
// That should give you 1000 (or 1001) every time.
Hmm. Don't forget that Serial.print() is unbuffered and takes close to 1ms per byte at 9600bps...
The originally posted prints the time that is the sum of times used by delay(1000), Serial.println(), and "lots of code." I'd expect that to be greater than 1000 for each loop()...
millis() returns the number of milliseconds that have elapsed since the beginning of your sketch. So each time through the loop, you will print the accumulated time between the start of your sketch and the point in your logic where you assign millis() to the variable time.
That means that you are printing the total elapsed time since your sketch started. That of course includes all the time it takes to execute all the code in your sketch, as westfw says.