Arduino: A Better Delay Function

You can find the full sketch code at the bottom of the page or you can download the .ino file from DropBox

The original delay function works fine in most cases, but quite often it is necessary to run code during the delay. If we write our own delay function we can accomplish this, and will also be able to add options.

I assign the name DELAY to a function and set it to take two variables. delayTIME for the amount of time to delay, and readPINS for the option to run a function when finished.


The formula for amount of time delayed is Time Started – Time Now = Time Delayed. Ts-Tn=Td.

Use a do..while loop to repeat until the amount of delay time is reached. Code in the loop will be executed during the delay. Do not call the delay function within the delay function itself. This will cause the code to break.


Place an if statement at the end of the function to check the readPINS option. If the value is true then it runs the function READPINS();


I redefined the original delay function as the new delay function. If you intend to use the original delay function along with the new one, then it is not necessary to redefine the function.


The line that calls the function looks like this.


Here is an example, I hope you give it a try!


//redefine original delay with our new function
#define delay DELAY

void setup() {

void loop() {
delay(1000, true);

void DELAY(long delayTIME, boolean readPINS){
//set var to current time
long tmpTIME = millis();

//loop until delaytime is reached
//code to execute while waiting
}while (millis() - tmpTIME < delayTIME);

//check if readpins is true
if (readPINS == true)

void READPINS(){