void循环可以独立运行吗?

Can void loops run independently?

基本上,我有一个连接到 16x2 LCD 屏幕的 Arduino Uno R3,我想在第 0 行的 16 秒内显示 3 个不同的文本,在第 1 行我想添加一秒钟柜台。启动它时,文本部分工作正常,但秒数计数器仅在显示所有 3 个文本的 16 秒后出现,显示数字 16。当这 3 个文本再次出现时,计数器现在将显示 32,然后是 48、64,所以来来回回。所以它只会在 16 秒后显示一些内容。

我希望它做的是显示过去的每一秒(例如 1、2、3、4、5、6)。这是我目前所拥有的:

#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
    lcd.begin(16, 2); 
}

void loop() {
    text();
    counter();
}

void text() {
    lcd.setCursor(6, 0);
    lcd.print("Text1");
    delay (8000);
  
    lcd.setCursor(6, 0);
    lcd.print("     ");
  
    lcd.setCursor(6, 0);
    lcd.print("Text2");
    delay (4000);
  
    lcd.setCursor(6, 0);
    lcd.print("     ");
  
    lcd.setCursor(6, 0);
    lcd.print("Text3");
    delay (4000);
  
    lcd.setCursor(6, 0);
    lcd.print("     ");
}

void counter() {
    lcd.setCursor(7, 1);
    lcd.print(millis() / 1000);
}

任何帮助将不胜感激。

Arduino 是单核控制器,因此如果没有额外的任务处理功能,您无法运行 并行执行多个循环。您最可能正在寻找的是 Superloop这基本上是一个无限循环,包含您系统的所有任务。如果计时条件匹配,则执行任务。

您可以在 Internet 和以下网站中找到大量关于它的介绍和文献:

您可以通过一种非常简单的方式实现这一点,例如:

void loop()
{ 
    //Check if task 1 needs to be executed
    if (millis() - task1LastMillis >= 100) 
    {
        //Get ready for the next iteration
        task1LastMillis = millis();
        myFunction1();
    }
    //Check if task 2 needs to be executed
    if (millis() - task2LastMillis >= 500) 
    {
        //Get ready for the next iteration
        task2LastMillis = millis();
        myFunction2();
    }
    //...
}

请注意,还有其他更复杂的选项,例如使用 RTOS 实现类似的多任务处理行为。