在永远循环或无效循环中执行一次(一次)?

Do one time (once) execution in forever loop or void loop?

我想在任何程序语言的永远循环(空循环)中制作一次或一次执行语法。

我发现解决方案是使新变量布尔值“执行”并在执行后设置为 true。

没关系,但是如果我想对其他语法执行一次怎么办?我应该再次创建新变量布尔值吗?它不会有效。想象有很多语法,但我必须为每种语法创建新的 bool executiin。

解决方案是我认为的函数

例如

void loop()
{
lcd.print("OK");
}

这将永远打印 我希望有这样的功能

void loop()
{
once(lcd.print("OK"));
}

所以“一次”是一个带有参数字符串的函数,它用于 command/syntax。

一次(“命令”)

这是一种方法:

void loop()
{
    { // execute once. Can put this in a separate function also
        static bool executed = (lcd.print("OK"), true);
    }
}

你保证这个变量被初始化一次。

如果你想在你的问题中使用 once 语法,你可以用宏实现类似的东西:

#define ONCE(...) \
{\
 static bool executed = ([&]{__VA_ARGS__;}(), true); \
}


void loop()
{
    ONCE(lcd.print("OK"))
}

解决这个问题的几种方法

以下是通常如何进行此类操作的一种非常常见的方式。 正如您已经建议的那样,使用 global boolean:

bool once = true; // global variable
void loop() {
  if (once) { // being called only once
    lcd.print("OK");
    once = false;
  }
}

只做一次在特定时间后:

void loop() {
  // millis() is the time in milliseconds after the startup 
  //if you want to print something once after a specific amount of time
  //this also includes a little "wait time" of 100 milliseconds as the statement might be asked with a delay
  if (mills() >= 1000 && mills() <= 1100) {// time in milliseconds
    lcd.print("OK");
  }
}

感谢 this 线程,退出循环(可能不是您要搜索的内容):

void loop() {
  lcd.print("OK");
  exit(0);  //The 0 is required to prevent compile error.
}

但我想你正在尝试制作某种界面,其中打印关于用户输入的特定答案(可能有多种可能性)?! 在那种情况下,这在某种程度上取决于您获得的输入:

整数的情况下

void loop() {
  switch (input) { //input must be an integer
    case 0:
      lcd.print("OK"); //prints "ok" if input is 0
    case 1:
      lcd.print("Hello"); //prints "Hello" if input is 1
  }
}

Stings/chars 的情况下,您需要使用“if 循环”遍历每个可能的输入(或使用 Strings/chars 的数组) :

void loop() {
  lcd.print("Turn off?"); //asks if it should do something
  if (input == "yes") { //String input
    lcd.print("OK, shut down!");
    //do something
  }
  else if (input == 'n' || input == 'N') { //char input
    lcd.print("OK, no shut down!");
    //do something
  }
}

您正在寻找的函数,其中特定答案仅打印一次关于输入的内容可以 仅通过 if/else 循环存档。如果一个 String 应该在启动时只打印一次,请在“setup()”构造函数中打印它。否则只要使用 global booleans 就可以实现类似的东西。

请注意,这些只是我根据我的经验提出的建议,但这并不一定意味着其他解决方案不可用。 希望仍然有帮助:)

在C++中,有std::call_once偶数multi_thread,那么可以通用:

template <typename F>
void simple_do_once(F f)
{
    static std::once_flag flag;
    std::call_once(flag, f);
}

因为 lambda 有唯一的类型,你有一个 lambda 标志:

Demo