// https://wokwi.com/projects/452599829277452289
// https://forum.arduino.cc/t/serial-monitor-proof-but-the-c-arduino-r3-acts-differently/1424032
const unsigned long LIMIT_TIME = 1000;
const byte LIMIT_TRIES = 4;
enum returnCode {OK, TIMEOUT, TOOMANY};
void setup() {
Serial.begin(115200);
Serial.println("\nhi Mom!\n");
}
void loop() {
Serial.println("gonna try... ");
returnCode result = tryThis();
switch (result) {
case OK :
Serial.println("successful");
break;
case TIMEOUT :
Serial.println("took too long!");
break;
case TOOMANY :
Serial.println("tried and tried and failed!");
break;
default :
Serial.println("never happens!");
for (; ; );
}
Serial.println("");
delay(1777);
}
returnCode tryThis()
{
int fails = 0;
unsigned long start = millis();
while (millis() - start < LIMIT_TIME) {
bool success = someProcess(); // true is success, this is an attempt
if (success) return OK; // we done, happy
fails++;
if (fails >= LIMIT_TRIES) return TOOMANY; // we outta here, too many attempts
}
return TIMEOUT; // ran out of time
}
bool someProcess()
{
int taking = random(100, 450); // mean ≈ 225 ms
delay(taking);
// ~25% chance of success
bool success = (random(4) == 0);
Serial.print(success ? " succeeded after " : " failed after ");
Serial.print(taking);
Serial.println(" ms");
return success;
}
bool someProcess0()
{
int taking = random(750, 1500);
delay(taking);
bool success = (taking & 1) ? true : false;
Serial.print(success ? " succeeded after " : " failed after ");
Serial.print(taking);
Serial.print(" ");
Serial.println("milliseconds");
return success;
}