Search code examples
c++arduinomicrocontrolleresp8266arduino-esp8266

sleep in function but not block other functions and code


I am on esp8266 module/microcontroller. I have never wrote in C++. Now I am trying to insert my own small "non blocking" function in one file file. My function should wait 5 seconds on background and then print something. But I don't want to delay whole initialization of meInit() for 5 seconds, it should be let's say parallel "non blocking" function. How is this possible please?

void meInit()
{ 
  if (total > 20) total = 20;
  value = EEPROM.read(1);

  Serial.begin(115200);
  Serial.setTimeout(10);

  loadSettings(true);

  buildMe();

  initFirst();

  //here I need to call "non-blocking" function with no delay and process immediatelly further
  call5sFunct();  

  ...do other functions here immediatelly without 5s delay...
}

void call5sFunct()
{
  Sleep(5000);

  DEBUG_PRINTLN("I am back again");
}

P.S. short sample is highly appreciated :) thx


Solution

  • You must not sleep at all, but just call your function after 5 seconds have passed, in the loop function. Something like this (untested):

    unsigned long start_time = 0;
    bool call5sFunct_executed = false;
    
    void meInit()
    { 
      if (total > 20) total = 20;
      value = EEPROM.read(1);
    
      Serial.begin(115200);
      Serial.setTimeout(10);
    
      loadSettings(true);
    
      buildMe();
    
      initFirst();
    
      // You cannot call it here, but in loop()
      // call5sFunct();  
    
      // ...do other functions here immediatelly without 5s delay...
    }
    
    void call5sFunct()
    {
      DEBUG_PRINTLN("I am back again");
    }
    
    void loop()
    {
       unsigned long loop_time = millis();
       if (!call5sFunct_executed && (loop_time - start_time >= 5000))
       {
          call5sFunct();
          call5sFunct_executed = true;
       }
       // .... the rest of your loop function ...
    }
    

    However, this template must be used extensively programming microcontrollers. It would be really coumbersome and error-prone to write production code like this - but it's important you get the point.

    There are many libraries that make it easy to implement asynchronous operations on arduino, hiding this mechanism. For example take a look to TaskScheduler.

    Google for "arduino asynchronous functions" and you will find a lot of alternatives.