代码之家  ›  专栏  ›  技术社区  ›  peter

休眠函数,但不阻止其他函数和代码

  •  0
  • peter  · 技术社区  · 8 年前

    我使用esp8266模块/微控制器。我从来没有用C++写过。现在,我正试图在一个文件中插入我自己的小“非阻塞”函数。我的函数应该在后台等待5秒钟,然后打印一些内容。但我不想将整个meInit()初始化延迟5秒,应该是并行的“非阻塞”函数。请问这怎么可能?

    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、 高度赞赏美国短样品:)thx

    2 回复  |  直到 8 年前
        1
  •  1
  •   Alexey Usachov    8 年前

    使用 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>

        2
  •  0
  •   Sigi    8 年前

    您根本不能睡觉,只需在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 。

    在谷歌上搜索“arduino异步函数”,你会发现很多替代方法。

    推荐文章