Multi-threading with Scheduler.

I am working on a program that works on Due and 7"LCD. The simplified version of code is blew. The program does following:

  • Displays a sequence of images when idling(splash).
  • Constantly listening to incoming commands from serial port and executes them.
  • As soon as an incoming command is received, the splash stops and command executes for as long as it needs.
  • The executing commands can be stopped if another incoming command is received.
  • The splash continues if no command has been received for certain amount of time.

So for I got 1 & 2 working, however I can’t figure out the rest. I am wondering if there are other libraries out there works better than Scheduler.

Run the code in Sketch, enter “cmd1” in monitor, you can see both “cmd1” and “splash” are running simultaneously, I want “splash” to stop. Run “cmd1” first and “cmd2” right after, you will see “cmd2” doesn’t interrupt “cmd1”, instead if waits “cmd1” to finish then executes.

Any clarification you need, please ask. Thanks in advance.

#include <Scheduler.h>

String cmd = "";
boolean ready4Cmd = false;

void setup() {
  SerialUSB.println("Begin program...");
  while (!SerialUSB) {}
  SerialUSB.begin(115200);
  Scheduler.startLoop(doCmd);
  Scheduler.startLoop(doSplash);
}

void loop() {
  delay(5000);
}

void cmd1() {
  SerialUSB.println("Executing cmd 1 - step 1");
  delay(3000);
  SerialUSB.println("Executing cmd 1 - step 2");
  delay(3000);
  SerialUSB.println("Executing cmd 1 - step 3");
  delay(3000);
}

void cmd2() {
  SerialUSB.println("Executing cmd 2 - step 1");
  delay(3000);
  SerialUSB.println("Executing cmd 2 - step 2");
  delay(3000);
  SerialUSB.println("Executing cmd 2 - step 3");
  delay(3000);
}

void doSplash() {
  SerialUSB.println("Displaying splash pic 1");
  delay(3000);
  SerialUSB.println("Displaying splash pic 2");
  delay(3000);
  SerialUSB.println("Displaying splash pic 3");
  delay(3000);
}

void doCmd() {
  readCmd();
  exeCmd();
  delay(1000);
  yield();
}

void readCmd() {
  SerialUSB.println("Reading command");
  while (SerialUSB.available()) {
    char inChar = (char)SerialUSB.read();
    if (inChar != '\n') {
      cmd += inChar;
    } else if (inChar != '\0') {
      ready4Cmd = true;
    }
  }
}

void exeCmd() {
  SerialUSB.println("Executing command");
  if (ready4Cmd) {
    if (cmd == "cmd1") {
      cmd1();
    } else if (cmd == "cmd2") {
      cmd2();
    } else {
      SerialUSB.println("cmd '" + cmd + "' not found");
    }
    cmd = "";
    ready4Cmd = false;
  }
}

You may find some useful ideas in Several Things at a Time. It does not need any scheduling library.

...R

Robin2:
You may find some useful ideas in Several Things at a Time. It does not need any scheduling library.

...R

Finally had chance to rework the code using your suggested concept. It worked out great! Thanks a bunch.