arduino Time Management More than 1 task without delay()


Example

If you have more than 1 task to execute repeatedly in different intervals, use this example as a starting point:

unsigned long intervals[] = {250,2000}; //this defines the interval for each task in milliseconds
unsigned long last[] = {0,0};           //this records the last executed time for each task

void setup() {
  pinMode(LED_BUILTIN, OUTPUT); //set the built-it led pin as output
  Serial.begin(115200);         //initialize serial
}

void loop() {
  unsigned long now = millis();
  if(now-last[0]>=intervals[0]){ last[0]=now; firstTask(); }
  if(now-last[1]>=intervals[1]){ last[1]=now; secondTask(); }
  
  //do other things here
}

void firstTask(){
  //let's toggle the built-in led
  digitalWrite(LED_BUILTIN, digitalRead(LED_BUILTIN)?0:1);
}

void secondTask(){
  //say hello
  Serial.println("hello from secondTask()");
}

To add another task to execute every 15 seconds, extend the variables intervals and last:

unsigned long intervals[] = {250,2000,15000};
unsigned long last[] = {0,0,0};

Then add an if statement to execute the new task. In this example, I named it thirdTask.

if(now-last[2]>=intervals[2]){ last[2]=now; thirdTask(); }

Finally declare the function:

void thirdTask(){
  //your code here
}