3

With the following:

Serial.begin(9600);

I am printing two values:

Serial.print(Input); 
Serial.println(Output);
delay(100);

I am measuring temperature and PWM signal.

What are the drawbacks of using delay?

jacefarm
  • 5,123
  • 5
  • 32
  • 44
Dinesh
  • 41
  • 3

2 Answers2

3

Here are a couple of drawbacks of using delay :

  • Inaccuracy

  • Unable to multitask

There is one good way to go make a delay without using delay(), it's by using millis(). See here for great examples of why millis() is better than delay() and how to maximize its capability.

wallyk
  • 53,902
  • 14
  • 79
  • 135
Dat Ha
  • 459
  • 1
  • 9
  • 14
0

It is usually fine to use delay() in simple programs. However, imagine you have 4 tasks:

  • T1 which you want to execute every 2s
  • T2 which you want to execute every 3s
  • T3 which you want to execute every 3.5s
  • Serial read task, which should read serial input as soon as it arrives

How would you deal with that using delay()? It is much better to use approach based on millis() or micros() functions, like here, or use the elapsedMillis library, which under the hood does the same, but makes a code a bit more readable.

The main idea, is that you want to have a sort of timers, that store a time elapsed from last reset. You check the state of these timers in every iteration of the loop() function, and if they finish, you execute associated task:

void loop() {
  if(isTimerDone(Tim1)) {
    T1();
    resetTimer(Tim1);
  }
  if(isTimerDone(Tim2)) {
    T2();
    resetTimer(Tim2);
  }
  if(isTimerDone(Tim3)) {
    T3();
    resetTimer(Tim3);
  }
  readSerialPort();
}

That way it is very easy to change timing for each task, as it is independent of other tasks. It is also easy to add more tasks to the program.

It is also true, that delay() (but also millis()) are innacurat,e in a sense that you are not guaranteed to have an exact timing. To be sure that a task is executed exactly after given time, you need to use interrupts, like in here (Arduino Playground on Timer1).

CL.
  • 158,085
  • 15
  • 181
  • 214
mactro
  • 486
  • 7
  • 13