Surely there's a command along the lines of .. invoke in .. 2000 .. method.
Not "a command" but you can make up something like that easily enough. Example:
// Function scheduler demo
// Author: Nick Gammon
// Date: 11 July 2015
typedef void (*GeneralFunction) (); // function pointer type
GeneralFunction wantedFunction = NULL; // function to call
unsigned long functionTimerStarted; // when the timer started
unsigned long delayPeriod; // how long to wait (ms)
void functionA ()
{
Serial.println ("Function A");
} // end of functionA
void functionB ()
{
Serial.println ("Function B");
} // end of functionB
void functionC ()
{
Serial.println ("Function C");
} // end of functionC
void functionX ()
{
Serial.println ("Function X");
} // end of functionX
void scheduleFunction (GeneralFunction f, unsigned long when); // prototype
void scheduleFunction (GeneralFunction f, unsigned long when)
{
wantedFunction = f;
functionTimerStarted = millis ();
delayPeriod = when;
} // end of scheduleFunction
void setup ()
{
Serial.begin (115200);
Serial.println ();
functionA (); // call this now
scheduleFunction (functionX, 2000); // call this later
functionB (); // call this now
functionC (); // call this now
} // end of setup
void loop ()
{
// see if time to call the delayed function
if (wantedFunction && millis () - functionTimerStarted >= delayPeriod)
{
wantedFunction ();
wantedFunction = NULL; // don't call it again
} // end of if time up
// do other wanted stuff here
} // end of loop
This uses:
- A function pointer to remember which function to call in the future.
- A global variable to remember when you wanted this timing interval to start.
- A global variable to remember how long to wait.
In setup() I called a function to save this information for future use:
scheduleFunction (functionX, 2000); // call this later
Then in loop() we see if the time is up, and then call the function.
This example just calls functions with no arguments, things will get more complex if you want to call a function with an argument. It would even be possible to remember the argument, but it may be unnecessarily complicated to explain how to do that, since your example did not ask for it.
You could also even schedule multiple functions, but again, showing all that adds to the complexity of the explanation.
For more information about function pointers, see Function pointers / function callbacks / function variables.