How to check if com Port is already being used by another application?

How do I check if com Port is already being used by another application or if it is free to be used ?

import processing.serial.*;

Serial myPort;

void setup(){
  myPort = new Serial(this, Serial.list()[0], 9600);  // How to check if this port is free or not ??
}

void draw(){
  serialPortCheck();
  serialReadData();
}

void serialPortCheck(){
  if(myPort.active()==false){
    println("Error in com Port");
  }
}

void serialReadData(){
  if(myPort.available()>0){
    println(myPort.readString());
  }
}

Hi
Port options

// display serial port list 
println(Serial.list());
printArray(Serial.list());
// get the first available port (use EITHER this OR the specific port code below)
String portName = Serial.list()[0];

// get a specific serial port (use EITHER this OR the first-available code above)
String portName = "COM5";

// open the serial port
port = new Serial(this, portName, 115200);



May in this links some hints if you looking for something else

1 Like

Hello,

I am sharing some code I experimented with:

// Serial Port State
// v1.0.0
// GLV 2022-07-15

import processing.serial.*;

Serial myPort, myPort2;

void setup(){
  
  printArray(Serial.list());
  
  //myPort = new Serial(this, Serial.list()[4], 9600);
  //try
  //  {
  //  myPort2 = new Serial(this, Serial.list()[4], 9600);
  //  }
  //catch(Exception e)
  //  {
  //  println(e);
  //  }
  }

void draw()
  {
  }

void serialReadData(){
  if(myPort.available()>0){
    println(myPort.readString());
  }
}

void keyPressed()
  {
  if(key == 'c')
    {
    println("connect");  
    try
      {
      myPort2 = new Serial(this, Serial.list()[4], 9600);
      }
    catch(Exception e)
      {
      println(e);
      }
    }
    
  if(key == 's')
    {
    println("stop");  
    try
      {
      myPort2.stop();
      }
    catch(Exception e)
      {
      println(e);
      }
    }
  
  if(key == 'i')
    {
    println("info:"); 
    if (myPort2 != null)
      println(myPort2.active());
    }
  
  //if(key == 'n')
  //  {
  //  myPort2 = null;
  //  println("null", myPort2);
  //  }
    
  if (key == 'r')
    {
    if(myPort2.available()>0)
      {
      println(myPort2.readString());
      }
    }
    
  if(key == 'l')
    {
    printArray(Serial.list()); 
    }     
  }    

Using try\catch was useful to determine state of port as “Port busy” or “Port not found”.

I was able to disconnect the Arduino (unplug) and connect to it again (after plugging back in) and receive data in Processing sketch without restarting the sketch… that is a positive sign.

:)

1 Like