looptime

From time to time you might need to have precise timing on your loop. If you want to do real time sampling, control, loggning and so forth.

Then looptime might be interesting for you.

The Problem

Using the delay function will NOT give you an exact looptime…

The problem below is that a single loop takes 100 milliseconds plus duration of do_some_code.


... code snippet

void do_some_code()
{
   analogRead(A3);
   calculate_PID(); // your code
   analogWrite(...);
}

void loop()
{
   do_some_code();  // need to run 10Hz (which is 100 msec pr loop)
   delay(100);  // wait 100 milliseconds
}

So we need to adjust the delay so the delay and time for exection of your code takes 100 milliseconds in this case.

The solution 1


unsigned long tOld,tNew,tWait;

void setup()
{
   ...
   ...
   tOld = millis();  // time in milliseconds
}

void loop()
{
    do_your_code();
    tNew = millis();              // what's the time now ?
    tWait = 100 - (tNew - Told);  // We need to wait 100 minus duration
    delay( tWait );
    tOld = tNew; // for next loop
}

I have written an easy solution for that - looptime

Looptime library

Easy to use:

#include <looptime.h>

void setup()
{
   ...
}

void loop()
{
   do_your_100millisecond_stuff();

   looptime(100); // datz all
}

If you want to be sure then looptime returns how long time it did wait by delay or it returns 0(zero) if you are behind

#include <looptime.h>

void setup()
{
   ...
}

unsigned long result;
void loop()
{
   do_your_100millisecond_stuff();

   result = looptime(100); // datz all
   if (0 < result) {
     // all is ok :-)
   }
   else {
     // we are behind
   }
}

Test example

In the example below eating time is done by delay. For every loop we do eat between 200 and 800 milliseconds
by use of random function iwhtin the delay call

We do use looptime to impose 1000 milliseconds for the loop

For check: We do print out how long time looptime waits and the time from millis function just after the looptime call.

You will (hopefully :-) see that waiting time in looptime varies but we will be right on the target line
for 1000 milliseconds loop time (or 1 Hz sampling)

BEWARE it might vary on last digit (plus/minus 1 millisecond) because this is the granularity of the millis timer

#include <looptime.h>

void setup() {

  Serial.begin(9600);
}
unsigend long res;

void loop() {
  delay ( random (200, 800) );

  Serial.print("looptime wait: ");

  res = looptime(1000);

  Serial.print(res);
  Serial.print(" time: ");
  Serial.println( millis() );
}

Cavecats

If you are using millis or looptime to impose a looptime close to 1 millisecond you will of course run into
some problem due to the granularity - that millis measure with 1 milliseconds accuracy.

So in practical life 100-200 Hz might be maximum samplingfrequency using looptime.

But test it :-)

Code

Jens