Delay function not accurate enough: use of mills?

Hi guys,

I have a function that needs to execute every n microseconds.

If I have
Void loop{
delay(200);
My function;
}

And myfucntion takes 100ms to complete then each loop will be 300ms. Not good.

How can I use the millis function to ensure the delay is taking into consideration the time it takes for myfucntion to complete?

Basically I need myfunction to start every 200ms regardless of the time it takes myfunction to complete. (obviously if myfunctiom takes more than 200ms I'll have problems but it's usually taking 2-3 to complete.

Cheers in advanced.

You could use my elapsed time class:

That way you do something after a specific time has elapsed.

MyFunction without delay ....

#define THRESHOLD  200
unsigned long lastTime = 0;

void setup()
{
  Serial.begin(115200);
  Serial.println("Start...");
}

void loop()
{
  if (millis() - lastTime >= THRESHOLD)
  {
    lastTime = millis();
    MyFunction(); 
  }
}

void MyFunction()  // replace by your own ..
{
  Serial.println(lastTime );
}

-- update --
Below there are some serious improvements (subtile but serious)

  if (millis() - lastTime >= THRESHOLD)
  {
    lastTime = millis();

I've never liked the idea of calling millis() twice like this, since it is possible to get two different values.

unsigned long thisTime = millis();
if(thisTime - lastTime >= THRESHOLD)
  {
    lastTime = thisTime;

This makes only one call to millis(), at the cost of 4 extra bytes on the head.

Definitely better to use the var thisTime as timing would indeed creep forward, thanks

For more accurate timing use this:

#define THRESHOLD  200
unsigned long lastTime;

void setup()
{
  Serial.begin(115200);
  Serial.begin("Start...");
  lastTime = millis();
}

void loop()
{
  if (millis() - lastTime >= THRESHOLD)
  {
    lastTime += THRESHOLD
    MyFunction(); 
  }
}

If you want to execute MyFunction immediately the first time loop() is called instead of waiting for THRESHOLD ms, then initialize lastTime to millis() - THRESHOLD instead in setup().

OK I see the difference, it is subtile but relevant ,

This variation should be documented too at the famous - http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay - Tutorial

Thanks dc42, still learning everyday :slight_smile: