A substitute for the delay() function in Arduino

Posted by

Hello guys, how are you doing today? 

   Ever since I came across the Arduino platform, I felt really pissed off with (the existence) of the delay() function. Let’s then implement a substitute for the delay() function in Arduino.

   I have rapidly created a counter to substitute this function in every sketch of my own, with the downside of having to adjust the counted number for every single program (because different program sizes take different times to be executed).

This scenario have just changed, because I am presenting you my very own professional way to not waste precious time of your Arduino. It is a sketch that allows you to run a piece of code every ‘x’ microseconds while leaving the rest of the time free for execution of more code!. 

   The code takes advantage of the micros() function, present in the stock Arduino language and IDE, which returns the time (in microseconds) that Arduino has been running since the last reset. 

Essentially what I do is to execute my main function (which I can freely choose) only every given time; this “given” time can be adjusted by updating its value (in microseconds) in an IF loop.

The code

   The sketch is available on my GitHub and doesn’t require any special library or installation, only the stock micros() function. Essentially your custom code, such as blinking leds, goes in between the quotes I have wrote (as seen below): 


   The main advantage in this code is that you can execute a code every ‘x’ microseconds (utilizing the sketch exactly as it is) or multiple codes every ‘y’ microseconds (by adding new IF conditions based on the same couter).

You can not forget to fill your setup() function as needed; your timing will always be respected, once you don’t write a code big enough (that takes more time than your delay) to be executed. 

Want to learn about another optimization technique for microcontrollers? see here.

5 responses

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA