delay without "delay()"



/*  Delay without "delay()"
 *   Chad Higgins 2012
 *   Demonstates how to use write a delay that is like "blink without delay" but is used much like "delay()"
 */


//This timer also overcomes the 50 day millis() limit problem
//this setup will allow 10 timers, 0-9,
//replace "10" with a higher or lower number if you need more or less timers
//the next two lines must be added to any program using this code
unsigned long timer[10];
byte timerState[10];



int ledState = HIGH;


void setup() {
  pinMode(13,OUTPUT);
  digitalWrite(13,HIGH);
}

void loop() {

//the number "1" is the timer used
//The next number "1000" is the delay in milliseconds
  if (delayMilliSeconds(1,1000)){
    if(ledState==HIGH){ledState=LOW;}
    else{ledState=HIGH;}
    digitalWrite(13,ledState);
  }
// Do something else here if enough time has not passed
}

//======================================
//Everything from here down comes after the main "loop()"

int delayHours(byte timerNumber,unsigned long delaytimeH){    //Here we make it easy to set a delay in Hours
  delayMilliSeconds(timerNumber,delaytimeH*1000*60*60);
}
int delayMinutes(byte timerNumber,unsigned long delaytimeM){    //Here we make it easy to set a delay in Minutes
  delayMilliSeconds(timerNumber,delaytimeM*1000*60);
}
int delaySeconds(byte timerNumber,unsigned long delaytimeS){    //Here we make it easy to set a delay in Seconds
  delayMilliSeconds(timerNumber,delaytimeS*1000);
}

int delayMilliSeconds(int timerNumber,unsigned long delaytime){
  unsigned long timeTaken;
  if (timerState[timerNumber]==0){    //If the timer has been reset (which means timer (state ==0) then save millis() to the same number timer,
    timer[timerNumber]=millis();
    timerState[timerNumber]=1;      //now we want mark this timer "not reset" so that next time through it doesn't get changed.
  }
  if (millis()> timer[timerNumber]){
    timeTaken=millis()+1-timer[timerNumber];    //here we see how much time has passed
  }
  else{
    timeTaken=millis()+2+(4294967295-timer[timerNumber]);    //if the timer rolled over (more than 48 days passed)then this line accounts for that
  }
  if (timeTaken>=delaytime) {          //here we make it easy to wrap the code we want to time in an "IF" statement, if not then it isn't and so doesn't get run.
     timerState[timerNumber]=0;  //once enough time has passed the timer is marked reset.
     return 1;                          //if enough time has passed the "IF" statement is true
  }
  else {                               //if enough time has not passed then the "if" statement will not be true.
    return 0;
  }
}

 

Share