Arduino Timing Question

I want my main loop as precise as possible without extra costs and extra hardware. For example, I want start my loop at the top of every second. After my code is executed I want to delay for the remainder of the second. What is the easiest and best way to accomplish this?

Something like this should do it. Replace the digitalWrites with your code.

unsigned long interval = 0;
void setup(){
pinMode (13, OUTPUT);
interval = millis();
void loop(){
if (millis() >=interval){
interval = interval+1000; // set up for next second
// do the code
digitalWrite (13, HIGH);
delay (100);
digitalWrite (13, LOW);

CrossRoads: Something like this should do it.

There is an alternative way to code that logic which deals with timer overflow correctly:

currentMillis = millis();
if(currentMillis  - previousMillis > interval)
    previousMillis = currentMillis;
    // your stuff goes here ...

This will run 'your stuff' approximately once per interval over an indefinite period.

If it's particularly important that you run 'your stuff' exactly once per interval, you would change this slightly, to:

    previousMillis += interval;

This avoids scheduling drift caused by the small delays between the interval passing, and your sketch noticing that it has passed. If that was important, you'd need to be using an accurate clock source too. For ordinary stuff that you just want to happen at approximately the right frequency you don't need to worry about that.

This might be a time to look into assembly language programming of your device.

I use the ArduiunoIDE to develop an idea, and if that is good timing wise I continue with it there. BUT sometimes you need just a little bit more and then assembly language opens up the whole chip. It is a little daunting to begin, but with a little trial and error (programming...) it starts to make sense. For that I personally use AVRStudiio 4 (5 is available, but it is way to sluggish for my taste).

You can't do it in the main loop, as it random process when your code will pass a line with millis() or microsecond next time. Depends on how big your program it could be more accurate with static code (no if's, while's, do-while's, serial etc) but never precise accurate. The same time it's a piece of cake to do it with timer, setting it to 1 second period, and put your code in TIMER_ISR(). Start with a library, MsTimer2 or Metro.