Modify the BlinkThreadCallback example so you run two threads that blink different LEDs once per second by waiting for each other

main.cpp

Committer:
vicara
Date:
2018-11-11
Revision:
1:30693312f670
Parent:
0:11ca69d691b7

File content as of revision 1:30693312f670:

#include "mbed.h"

DigitalOut led1(LED1);
DigitalOut led2(LED2);
InterruptIn button(USER_BUTTON);

//____________________________

Thread thread1;
Thread thread2;

//____________________________

bool is_debug_enabled = false;
bool is_t2_done = true;
bool is_t1_done = false;

void toggle_debug_mode() {
    is_debug_enabled = !is_debug_enabled;
}
 
void led1_thread(DigitalOut *led) {
    if(is_debug_enabled)
        printf("T1 STARTED\n");
    while (true) {
        if(is_t2_done){
            if(is_debug_enabled)
                printf("T1 EXECUTING\n");
            is_t1_done = false;
            is_t2_done = false;
            *led = !*led;
            wait(1);
            *led = !*led;
            is_t1_done = true;
            if(is_debug_enabled)
                printf("T1 DONE\n\n");
        }  
    }
}
 
void led2_thread(DigitalOut *led) {
    if(is_debug_enabled)
        printf("T2 STARTED\n");
    while (true) {
        if(is_t1_done){
            if(is_debug_enabled)
                printf("T2 EXECUTING\n");
            is_t1_done = false;
            is_t2_done = false;
            *led = !*led;
            wait(1);
            *led = !*led;
            is_t2_done = true;
            if(is_debug_enabled)
                printf("T2 DONE\n\n");
        }  
    }
}
 
int main() {
    button.rise(&toggle_debug_mode);
    thread1.start(callback(led1_thread, &led1));
    thread2.start(callback(led2_thread, &led2));
    thread1.join();
    thread2.join();
}