Multi Task in Arduino [closed]

1

How can I do multiple tasks in arduino without using the function delay() and that each task is executed during a certain period and the tasks can run in parallel.

void setup() {
    //TODO: ...
}

void loop() {
    task1();
    delay (...);
    task2();
    delay (...);

    ...

    taskN();
    delay (...);
}
    
asked by Luis Miguel Baez 12.08.2018 в 22:08
source

1 answer

2

I was consulting in books and I found this solution that works perfectly for me

void setup() {
    //TODO: ...
}

void loop() {
    task1();
    task2();
    task3();
}


void  task1() {
    //{period}: Periodo de Tiempo en el cual se va a ejecutar esta tarea
    unsigned long period=200; //En Milisegundos

    static unsigned long previousMillis=0;

    if((millis()-previousMillis)>period){
        // ---------------------------------
        // TODO:
        // Codigo de la Tarea 
        // ...
        // ---------------------------------
        previousMillis += period;
    }  
}

void  task2() {
    //{period}: Periodo de Tiempo en el cual se va a ejecutar esta tarea
    unsigned long period=500; //En Milisegundos

    static unsigned long previousMillis=0;

    if((millis()-previousMillis)>period){
        // ---------------------------------
        // TODO:
        // Codigo de la Tarea 
        // ...
        // ---------------------------------
        previousMillis += period;
    }  
}

void  task3() {
    //{period}: Periodo de Tiempo en el cual se va a ejecutar esta tarea
    unsigned long period=1000; //En Milisegundos

    static unsigned long previousMillis=0;

    if((millis()-previousMillis)>period){
        // ---------------------------------
        // TODO:
        // Codigo de la Tarea 
        // ...
        // ---------------------------------
        previousMillis += period;
     }  
 }

Each of the tasks has a variable period that indicates the period in which this task will be executed this period is in Milliseconds .

there is another variable estatica called previousMillis which is what will act as a counter for the task to be executed in the period described.

    
answered by 12.08.2018 / 22:32
source