// for https://forum.arduino.cc/t/how-can-i-run-two-loops-at-the-same-time/1151388/12?u=davex
// https://wokwi.com/projects/371242906116762625
void setup() {
Serial.begin(115200);
}
void loop(void) {
// choose one scheme:
switch (3) {
case 1: loopTimeLineDelays(); break;// use delays() to run a timeline
case 2: loopTimeLine(); break; // do stuff during the delays in the timeline
case 3: loopNonBlocking(); break; // do a non-blocking timeline with a state machine
}
}
void loopTimeLineDelays() {
// Serial code
Serial.print("\nA");
delay(1000);
Serial.print('B');
delay(1500);
Serial.print('C');
delay(500);
Serial.print('D');
delay(1000);
// try the other actions after the serial timeline runs:
otherThing2();
otherThing3();
otherThing4();
}
void loopTimeLine() {
// Serial code with delay()s replaced by special cooperative delay function:
Serial.print("\nA");
doOtherThingsWhileDelaying(1000);
Serial.print('B');
doOtherThingsWhileDelaying(1500);
Serial.print('C');
doOtherThingsWhileDelaying(500);
Serial.print('D');
doOtherThingsWhileDelaying(1000);
}
void loopNonBlocking() {
nonBlockingThing1();
otherThing2();
otherThing3();
otherThing4();
}
void doOtherThingsWhileDelaying(unsigned long msDelay) {
unsigned long startTime = millis();
while (millis() - startTime < msDelay) {
otherThing2();
otherThing3();
otherThing4();
//...
}
}
bool otherThing2(void) {
const unsigned long interval = 333;
static unsigned long last = millis();
if (millis() - last < interval) return false;
last = millis();
Serial.print('2');
return true;
}
bool otherThing3(void) {
const unsigned long interval = 777;
static unsigned long last = millis();
if (millis() - last < interval) return false;
last = millis();
Serial.print('3');
return true;
}
bool otherThing4(void) {
if (Serial.available()) {
char ch = Serial.read();
Serial.print(ch);
return true;
}
return false;
}
void nonBlockingThing1(void) {
static int state = 1;
static unsigned long interval = 0;
static unsigned long last = 0;
if (millis() - last >= interval) {
last = millis();
switch (state) {
case 1:
Serial.print("\nA");
interval = 1000;
state = 2;
break;
case 2:
Serial.print('B');
interval = 1500;
state = 3;
break;
case 3:
Serial.print('C');
interval = 500;
state = 4;
break;
case 4:
Serial.print('D');
state = 1;
interval = 1000;
break;
}
}
}