Alternatives to delay()

hi,

just built my first project with Arduino. Was hoping to optimize it in a few ways (reduce global variables, lesser string variables etc.) when i stumbled upon a few posts saying that delay() was for beginners and that millis() was more useful when multi-tasking... although using either is entirely dependent on the context of the application. I use delay() several times in my project, especially when I want text to be displayed for a minimum amount of time on an LCD screen.

However, I was wondering if delay() could always be replaced by millis() - would that be "optimizing" my code ? please let me know.

thanks!

"millis()" is not a drop in replacement for "delay()".
See the "Blink Without Delay" Example in the IDE. It is a different approach to do time management.

That is not complete true. It is useful function. However, the MCU is in no operation loop during the delay function except yield(), if it is defined.

Look at the BlinkWithoutDelay example.

Hello ghoshofx1

That´s true.

You can use the delay() function if you are running a single task on the Arduino.

If you have serval tasks with a dedicated timing behaiviour it is usefull to have time slices based on millis() function.

Take as aready mentioned the BlinkWithOutDelay example of the IDE and use this example to design your timer() function.

This timer() function might provide the following methodes:

start();
stop(),
event();
isRunning();

Have a nice day and enjoy coding in C++.

The most obvious impact of delay() vs millis() timing is when you are needing something to perform an action 'now' - e.g. a button press or critical event / message incoming.

Using delay(5000) - e.g. wait for 5 seconds while something is happening... note that nothing - means NOTHING - including the button press or other time critical event - wil lbe handled until the delay period is complete.

With well structured program flow, millis() (or any other similar non-blocking method), can check your input triggers far more often - allowing the button or external event to happen 'immediately'. The delay()s become irrelevant, because your program is 'event' driven, not bound to 'waiting' for some fixed time period to be complete.

Note - you will also learn about 'debouncing' slow events, because the processor is much faster than the switch contacts...
Then you may look into 'state-machines' which allow a number of things to happen (apparently at the same time) in almost any order.

Optimize for what?
Your code probably not became faster or shorter with millis(). But if you need that your program be able to do something else while the waiting for delay() is finished - you probably need to replace delay() with millis.
But if you program shouldn't do anything during the delay() - you don't need to change the code.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.