休眠功能但不阻止其他功能和代码

sleep in function but not block other functions and code

我在 esp8266 module/microcontroller。我从来没有用C++写过。现在我试图在一个文件文件中插入我自己的小 "non blocking" 函数。我的函数应该在后台等待 5 秒,然后打印一些东西。但我不想将 meInit() 的整个初始化延迟 5 秒,应该是并行 "non blocking" 函数。请问这怎么可能?

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。非常感谢简短的示例:) thx

使用std::thread在其他线程中启动call5sFunct();,像这样:

//...
initFirst();

//here I need to call "non-blocking" function with no delay and process immediatelly further
std::thread t1(call5sFunct);
t1.detach();  
...do other functions here immediatelly without 5s delay...

//...

您需要包括 #include <thread>

你绝对不能睡觉,而是在5秒后调用你的函数,在循环函数中。像这样(未经测试):

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 ...
}

但是,此模板必须广泛用于微控制器编程。像这样编写生产代码真的很麻烦而且容易出错 - 但重要的是你明白了。

有很多库可以很容易地在arduino上实现异步操作,隐藏了这个机制。例如看看 TaskScheduler.

Google for "arduino asynchronous functions" 你会发现很多选择。