Loop through serial ports

Loop through serial ports

Hello,
I am trying to make a while loop for searching of the right serial port. I get the “RuntimeException: Error opening serial port COM4: Port busy” error probably because the port connection is still open. For my understanding there should be a command like “close.myPort”.

while (firstContact == false){  
for (int i = 0; i <= Serial.list().length-1; ++i)
  {
  myPort = new Serial(this, Serial.list()[i], 9600);
  val = myPort.readStringUntil('\n');
  val = trim(val);
    if (val != null) 
    {
      if (val.equals("K")) 
      {
      firstContact = true;
      portNumber=i;
      myPort.write("O");
      println("contact");
      }
      else {println("no contact");}
    }
  }
}

Sorry if the solution is too simple but I could not google the answer.

I think you cannot simply “close” the port because other applications can be using it. Perhaps you can wrap inside the for loop with try/catch not to abort the program
https://processing.org/reference/catch.html

To clarify, the for loop (first run) works in the example above. The error occurs when it get called second time, because it can’t do myPort = new Serial(this, Serial.list()[i], 9600); again for same port.

oh. In that case why wouldn’t you keep the already-opened port variable and use it later?

It is here:
Serial / Libraries / Processing.org

:)