October 21, 2014

A substitute for the DELAY function - Arduino

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, because it was created with the (evil) solo purpose of wasting time between executions of the loop() function. 
   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 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, since you don't write a code big enough (that takes more time than your delay) to be executed. 
   
   I would greatly appreciate to hear from you guys, any suggestion, criticism, upsides, downsizes, anything that can make the code work better. You can reach me on twitter @embedded_clovis or email: clovisf AT gmail DOT com .