7 years, 1 month ago.

Running two while loop in parallel

I'm quite amature with mbed and C++ program. I'm trying to run two while loop in parallel at the same time and completely independent from one another. Both while loops have different function, for loops repeating time and waiting time. Anyone have any idea how to do it?

Here is the simplified version of my program

#include "mbed.h"

DigitalOut myled(LED1);
DigitalOut myled2(LED2);

int main() {
    while(1) { // Simplified version of function A
        (int x = 0; x <= 5; x++) { 
        myled = 1;
        wait(0.5);
        myled = 0;
        wait(0.5);
        }
        myled = 1;
        wait(1);
        myled = 0;
        wait(1);
    }
    while(1) { // Simplified version of function B
        (int x = 0; x <= 10; x++) {
        myled2 = 1;
        wait(0.2);
        myled2 = 0;
        wait(0.2);
        }
        myled2 = 1;
        wait(2);
        myled2 = 0;
        wait(1);
    }
}

2 Answers

7 years, 1 month ago.

Hi WB,

I think that you need an Operating System. This allows you to run different threads in parallel. Take a look at the RTOS page.

You can for instance have one of your loop in the "main" thread and the other loop in another thread:

#include "mbed.h"
#include "rtos.h"
 
void second_loop_thread(void const *argument) {
    while (true) {
        your_second_loop;
    }
}
 
int main() {
    Thread thread(second_loop_thread);
    
    while(1) {
        your_first_loop;
    }
}

Sam

Accepted Answer
7 years, 1 month ago.

RTOS is a good solution for larger, complex and especially not very timing sensitive systems.

For the time-base you shown in your example and the kind of functions it can work good. But generally using timer interrupts (for example the ticker is a good one: http://mbed.org/handbook/Ticker) is imo a neater solution. Less overhead and a more accurate timing.