c++arduino

How do I make a function that can be executed every certain interval inside a void loop?


I want to make a function like a void loop in which that function can execute another code for a certain interval.

unsigned long NOW;

void setup() {
}

void loop() {
  
  void doEvery(2){ //do Every 2 second
    //Put Code that Execute every 2 second
  }

  void doEvery(4){ //do Every 4 second
    //Put Code that Execute every 4 second
  }

}

How to declare/define function doEvery? I think that function must contain this:

if(millis()-NOW>=EVERY){
NOW=millis();
//THE LINE CODE
}

Solution

  • Taking THIS as initial idea:

    unsigned long previousMillis2 = 0, previousMillis100 = 0;
    
    void setup() {
    }
    
    void loop() {
      unsigned long currentMillis = millis();
    
      //doEvery 2
      if (currentMillis - previousMillis2 >= 2) {
        previousMillis2 = currentMillis; //stores last execution's timestamp
        //CODE EVERY 2  millis
      }
    
      //doEvery 100
      if (currentMillis - previousMillis100 >= 100) {
        previousMillis100 = currentMillis; //stores last execution's timestamp
        //CODE EVERY 100  millis
      }
    }
    

    With this, you will use millis() to ask for how many millis passed since initialization of Arduino. Then you store last time you executed your code and compare how many time passed since it. It's not a dynamic function for defining new intervals but if you only need a pair of it, you can code it easily.

    EDIT:

    If you need something more dynamic, you should use anonymous functions. SEE THIS or THIS The point here is function as parameter.