Search code examples
functionarduinodelay

How to create a stand alone arduino timing function? Is it possible?


I would like to create a function with two arguments. Argument 1 needs to be a time delay. Argument 2 will be another function that will execute when the appropriate time has elapsed. The last thing, is that i will use this function over and over. I would use it like this:

void loop()
{
   //code

   desiredFunction(1000, functionToRun(someArg));

   //code   

   desiredFunction(2000, anotherFunctionToRun(someArg));

   //more code

}

I could even omit argument 2 and replace it with a boolean which I can use to control an if statement. The most important thing is that I can have a delay which is fully housed in a stand alone function (without any global variables - to prevent any overwriting if I use the function many times)

My code is event driven and I cannot use the "delay()" function. At the same time I don't want to use the code below as it forces you to define a long global variable every time you use it and it would clutter the heck out of my code. If some one brilliant can figure out how to write a method such as i am describing I would be incredibly appreciative. I would put your name in my computing shrine :-)

  long previousMillis = 0;

  void setup()
  { 
  }

  void loop()
  {
     unsigned long currentMillis = millis();

     if(currentMillis - previousMillis > interval) 
     {
         previousMillis = currentMillis;  
         //do stuff
     }
  }

Thanks for your help.

Mike.


Solution

  • No need to reinvent the wheel, there are many libraries out there that will do this for you.

    http://playground.arduino.cc/Code/SimpleTimer (probably the simpler one). http://playground.arduino.cc/Code/Timer

    As for passing a variable, if no libraries support it, you can use a global variable that both the timed event and main flow of code can use.