Stop while (myPort.available() > 0)

Hi, beginner here, so please be gentle :slight_smile:

I am trying to stop a while look if a timer runs out (millis(). But I just cannot find a way of doing it.
What I am trying to do is if a certain string is not received before the timer reaches the target time, I want it to get out of the while loop. I tried all I can to my knowledge, and also searched online. No answer found, perhaps i didn’t search the correct words :frowning:

So, here is my current code. The variable “DumpActive” is set true by a button.

The line println(“Dump Aborted”); is displayed if there is data transfer from the Arduino, It shouldn’t. When data didn’t start flowing, and the time is up, this line should be displayed, and the while loop exited.
Thank you.

 if (DumpActive) {
  
    myPort.write("RequestEEprom");
    myPort.write('\n');

    while (myPort.available() > 0) {

      inData = myPort.readStringUntil('\n');
      if (inData != null) {
        inData = inData.trim();


        if ("END".equals(inData)) {
          SerialCheck = true;
          EEpromReceived = true;
        }
        if (!SerialCheck) {
          EepromData[SlotCount] = inData;
          //  println(inData);
        }

        inData = "";
        if (SlotCount > 16383) SlotCount = 0;
        SlotCount = SlotCount + 1;
      }
       if (TimerDump + 4000 < millis()) {         
         if(inData == null) {
           DumpActive = false;
          SerialCheck = true;
          println("Dump Aborted");
         }
       }
      if (SerialCheck) {

        SlotCount = 0;
        SerialCheck = false;
        DumpActive = false;

        AquireData();
      }
    }
  }

Hi @jhsa, For escaping a loop use break. Hope this code makes it obvious. Note the ++ as well, you need that.

int x = 0;

while (true){
  print(x); print(" ");
  if (x >= 10) {
    break;
  }
  x++;
}

Thanks, I tried using break; on the loop above, but it doesn’t work. that is a serial receiving loop.
Perhaps I am overlooking something…

JoĂŁo

Different ways forward: Put a print statement in all significant places in the code, run it for a few seconds, stare at the printed output, realise what’s wrong. Post the Processing and Ard sketches in full so someone else can try them (If it doesn’t need special hardware). Debug it (usually doesn’t have the right timing for Serial).

The timeout code will never execute if nothing comes in the serial port. It will reach the while (myPort.available() > 0) and drop right through.

inData = myPort.readStringUntil('\n'); will also block until a newline is received (which is forever, if nothing is connected).

Have a look at using serialEvent() to handle your incoming serial instead. That will allow your draw() loop to run and handle the timeout while you are waiting.