Home > OS >  Can void loops run independently?
Can void loops run independently?

Time:11-07

Basically, I have an Arduino Uno R3 hooked up to a 16x2 LCD screen and I want to make 3 different texts appear in the span of 16 seconds on line 0, and on line 1 I would like to add a seconds counter. When starting it the text portion works just fine but the seconds counter only appears after the 16 seconds when all 3 texts have been shown, showing the number 16. When those 3 texts appear once more the counter will now say 32 then 48, 64 so on and forth. So it only shows something after 16 seconds have passed.

What I would like it to do is show every second that has passed (for example 1, 2, 3, 4, 5, 6). Here is what I have so far:

#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);
}

Any help will be greatly appreciated.

CodePudding user response:

Arduinos are single core controllers, so you are not able to run multiple loops in parallel without additional tasking features. What you most propably are looking for is called the Superloop. This is basically an endless loop, containing all tasks of your system. Tasks are then executed if a timing condition matches.

You can find a lot of introduction and literature to it in the internet and sites like:

You can achieve this in a very simple way like:

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();
    }
    //...
}

Note that there are other but more complicated options like using RTOS achieving similar multitasking behaviours.

  • Related