c++ - 在forever循环或void循环中执行一次(once)吗?

标签 c++ c oop arduino

我想为任何程序语言在永远循环(void循环)内创建一次或一次执行语法。

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

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

解决方案是我认为的功能

例如

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

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

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

所以“once”是一个带有参数字符串的函数,用于命令/语法。

一次(“命令”)

最佳答案

解决这个问题的几种方法

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

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循环”:

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 循环进行存档。如果一个字符串应该在启动时打印一次,请在“setup()”构造函数中打印它。否则,只需使用全局 bool 值,类似的事情是可能的。

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

关于c++ - 在forever循环或void循环中执行一次(once)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65261874/

相关文章:

c++ - 一个类可以继承自另一个具体化的类模板吗?

c++ - 我可以将虚函数中的this指针视为派生类的this指针吗

c - sprintf 的 MISRA 兼容替代品?

javascript - 没有引用javascript的克隆对象

javascript - C++ - IWebBrowser2 - Javascript 未激活

c++ - 在 c 中调用 MPI_Finalize() 的段错误

c - 联动错误 :multiple definitions of global variables

c - 为什么即使我没有返回对象,我的结构也会被清零?

c++ - 返回 C++ 对象 - 最佳实践

c++ - 构造函数只能在类外定义