idefeat
Programming the Arduino with Visual Studio
May 8, 2016
particle
Spark Core / Particle – Room Temp/Humidity Monitoring & Mobile App
May 9, 2016
Show all

Scheduling Arduino Code (run every x seconds)

codes

Arduino code by nature runs in an infinite loop() and everything gets executed every cycle, unless you are using conditional elements and determining when to execute certain code. Any delay() you add to the code within the loop() will also halt the program before continuing.

The following code is extremely useful, for example, imagine you have an environment monitor and you would like to check LDR values every 1 hour, check temperature every 10 minutes, humidity/pressure every 30 minutes…

The framework below will allow you to specify when to run certain functions, be it every 100ms, 10s or 1 hour. It will only run code when you specify.

typedef struct t  {
    unsigned long tStart;
    unsigned long tTimeout;
};

//Tasks and their Schedules.
t t_func1 = {0, 100}; //Run every 100ms
t t_func2 = {0, 2000}; //Run every 2 seconds.

bool tCheck (struct t *t ) {
  if (millis() > t->tStart + t->tTimeout) return true;    
}

void tRun (struct t *t) {
    t->tStart = millis();
}

void setup (void) {
  //Arduino setup.
}

void loop (void) {
    if (tCheck(&t_func1)) {
      func1();
      tRun(&t_func1);
    }
    
    if (tCheck(&t_func2)) {
      func2();
      tRun(&t_func2);
    }
}

void func1 (void) {
  //This executes every 100ms.
}
void func2 (void) {
  //This executes every 2 seconds.
}

The code works by first defining your functions, in the example above func1() and func2(). We then add a variable for each of these functions called t_func1 and t_func2 which contain (in milliseconds) the interval in which they should be executed.

The loop() function then becomes a checker, it constantly checks the intervals on the functions and calls the functions when the millis() reaches the one we specified.

From this we then gain:

  • Structure to our code. All of our program is split into different functions, we know what is happening at what interval.
  • Run portions of code at user defined intervals.
  • Program speed. Less delay() to get the timings right and faster execution.
  • Less than 2% of program storage space used, easy to use light framework for scheduling.

The above code should be compatible with every version of the Arduino.

Leave a Reply

Your email address will not be published. Required fields are marked *