Reputation: 41
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?
Upvotes: 3
Views: 538
Reputation: 518
It is usually fine to use delay()
in simple programs. However, imagine you have 4 tasks:
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).
Upvotes: 0
Reputation: 650
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.
Upvotes: 3