Check For USB Port Connection

My sketch seems to work well unless I forget to plug in the USB-based input (Arduino). If I fail to connect the USB, my sketch fails in a most ungracious manner(appears to lockup in a loop). Can someone help with the code that will test for the presence of the USB input and terminate with an error message if it is no?

GPSPort = new Serial (this, Serial.list()[0],115200); // Live data comes thru a com port

Maybe you can use an if statement:

if (Serial.list() != 0) {
    ...
}

or a while statement:

while (myPort.available() > 0) {
    ...
}

Is it the Arduino side or the PC side that is locking up? Do you get an error message me
or just a freezing? Have you tried adding a try / catch block, and did that work?

Its the PC side that locks up. I don’t know what what a try/catch block is. Something I can read on it?

The try part goes around the place where the error is happening and the catch part gives instructions for what to do in case of a specific error message.

https://processing.org/reference/try.html

The following is my code that will work but its not the best to be sure:

boolean gotport = false;
if (Serial.list().length > 0 ) gotport = true;
if (gotport == false){
println (“Plug in the Arduino”);
exit();

} else {

GPSPort = new Serial (this, Serial.list()[0],115200);
GPSPort.bufferUntil(Linefeed);
println (“GPS Monitor starts . . .”);
}

Sure would appreciate some thoughts on how to make this a bit more elegant.

Hello,

Can you please format your code.
It helps (readability and testing) the people that may want to assist.

https://discourse.processing.org/faq#format-your-code

Try cutting and pasting your unformatted code into processing and you will see why.

I like to test code and may pass on it if it is not formatted…

1 Like
boolean gotport = false;
if (Serial.list().length > 0 ) gotport = true;             // i think this is weak but I dont know what else to do
if (gotport == false){
    println ("Plug in the Arduino");
    exit();
}  else  {
   GPSPort = new Serial (this, Serial.list()[0],115200);                           
   GPSPort.bufferUntil(Linefeed);
   println ("GPS Monitor starts . . .");
}

I should have thought of that sorry

1 Like

Hello,

Nice formatting!

This is a minimal version that I am sharing and assumes that:

Serial.list()[0]) is “COM3” //My Arduino; one of many!

I have many Arduinos and what ends up in Serial.list()[0]) depends on what is connected at the time and fills up lowest to highest COM port.

Here is a version close to what you did:

import processing.serial.*;

// The serial port:
Serial myPort3; 

boolean serialState = false;
//boolean lastSerialState = true;

boolean comState = false;

void setup()
  {
  background(255, 0, 0);
  
  // List all the available serial ports:
  printArray("Serial ports available: "); 
  printArray(Serial.list());
  println();
      
  // If you are trying to connect to a specific COM port by name
    String comPort = "COM3";
    comState = false;
    while(!serialState)
      {
      if ((Serial.list()[0]).equals(comPort))
        {
        comState = true;  
        }
        
      if (comState)
        {
        println("Arduino is connected");
        myPort3 = new Serial (this, "COM3", 9600);
        serialState = true;
        }
      else
        {
        println("Connect Arduino");
        serialState = false;
        }
      }
    }
  
  void draw()
    {
    background(0, 255, 0);
    }

I only posted minimal code to keep it simple and to the point; there is so much that can be done with this.
The version I wrote and work with (not posted) checks through serial.list(), COM ports, allows me to chose a COM port, prints messages only once to prompt user, etc.

Waiting to see if that while() loop ever times out… :slight_smile:

Enjoy!

1 Like

Thank you very much. I have, once again, proven to be adept at copying someone else’s code.

Fred

Here is the code that I entered in my sketch for the com port:

tvoid setup(){
int i = 0;  
boolean serialState = false;
//boolean lastSerialState = true;
boolean comState = false;
String comPort = "COM3";

comState = false;
while(!serialState) {
   if ((Serial.list()[0]).equals(comPort)) comState = true;  
   if (comState){
        println("Arduino is connected");
        GPSPort = new Serial (this, Serial.list()[0],115200);                           
        GPSPort.bufferUntil(Linefeed);
        serialState = true;
   }  else  {
        println("Connect Arduino");
        serialState = false;
   }
}

fullScreen(); ype or paste code here

The code “GPSPort = new Serial (this, Serial.list()[0],115200);” generated an array out of bounds exception. The Arduino was not connected and therefore there were no serial ports hence no array

1 Like

My original code loops through the Serial.list() and works for the scenario of no COM ports; I trimmed it down just for you.

Try this version:

import processing.serial.*;

Serial myPort3; 

boolean serialState = false;
boolean comState = false;

void setup()
  {
  background(255, 0, 0);
  
  // List all the available serial ports:
  printArray("Serial ports available: "); 
  printArray(Serial.list());
      
  // If you are trying to connect to a specific COM port by name
    String comPort = "COM3";
    comState = false;
    while(!serialState)
      {
      for (int i = 0; i< (Serial.list()).length; i++)
        {
        if ((Serial.list()[i]).equals(comPort))
          {
          comState = true;  
          }
        }
        
      if (comState)
        {
        println("Arduino is connected");
        myPort3 = new Serial (this, "COM3", 9600);
        serialState = true;
        }
      else
        {
        println("Connect Arduino");
        serialState = false;
        }
      }
    }
  
  void draw()
    {
    background(0, 255, 0);
    }
    
void serialEvent(Serial myPort3) 
  { 
  //https://processing.org/reference/libraries/serial/serialEvent_.html
  }    

As an exercise try to make it only prompt once to “Connect Arduino”.
I gave you a hint in the previous code.

1 Like

You get better at it… writing code that is.

Your original post inspired me to work through all the different scenarios when connecting to COM ports; I have a much better understanding of it all.

The suggestions by @BrokenCode did not work in this case but furthered my exploration of this as well.

I did not post the most elegant solution but I never tried this so consider it a success to build on.
This being “Auto connect to a fixed COM port and a while() loop in setup().”

1 Like

I understand what you are suggesting and it works. I have another question (its Windows) but I will ask it anyway: using the Device Manager to look at my ports, it came up “Arduino Uno (COM3)”. I am wondering if there is a way to get to the wording “Arduino Uno” as a way to verify the correctness of the port?
My thanks again for your help!
Fred

You are welcome.

I am not aware of a way to do this.

I was considering labeling my Arduinos with COM port but this is only useful at home on my PC where they are stored in the registry and will change with every other PC I connect to.

I always check COM ports before using devices on a different PC and select or add to my code.

In a future exercise, I am going to write some code to:

  • Read existing ports
  • Read ports after plugging in Arduino.
  • Determine which new port was added
  • Connect to new port

I am not asking the community for help with my future exercise; if I am stuck I will ask. :slight_smile:

Good Morning. I thought I might bother you again to consider an extension to what we were working on in this session. I wanted message printed on the screen to say “Plug in the Arduino” if not plugged in or “Searching for Satellites” if it was. the code is as follows:

//........................  Test for the presence of the Arduino. if there say its "searching for saltellites" otherwise tell the operator to plug in the Aduino
comState = false;
while(!serialState) {
   if (Serial.list().length >0 && Serial.list()[0].equals(comPort)) comState = true;  
   if (comState == true){
        Opmessage ("Searching for satellites . . .");
        GPSPort = new Serial (this, Serial.list()[0],115200);                           
        GPSPort.bufferUntil(Linefeed);
        serialState = true;
   }  else  {
     println("got here");
        Opmessage ("Plug in the Arduino GPS Scanner");
        delay (1000);
        serialState = false;
   }
}

Opmessage is as follows:

void Opmessage (String Message){
  background (black); 
  textSize(150);
  fill (red);
  textAlign (CENTER,CENTER);
  text (Message,SYS_Width/2, SYS_Height/2);
}//......................  End of opmessage

Please note that this all seems to work except the screen does not show the message to plug in the Arduino bit the message “got here” does show up.

Do you have any idea why the message does not appear until the Arduino is plugged in?

1 Like

Try a smaller textSize() that is <= 100.

Code below works to a maximum textSize(100) and displays in both setup() and draw() in Processing 3.5.4.

It does not display in setup() with Processing 4 Alpha 1.

void setup() 
	{
  size(1000, 360);
  background (255, 0, 0);
  
  println("got here");
  
  textSize(48);
  textAlign (CENTER,CENTER);

  text("Setup", width/2, height/4);               //Works!
  
  Opmessage ("Plug in the Arduino GPS Scanner");  //Works now!
  delay (2000);
	}

void draw() 
	{
  background(0, 255, 0);
  text("Draw", width/2, height/2);                //Works!
	}

void Opmessage (String Message)
  {
  text (Message, width/2, height/2);
  }

You will have to be quick to plug it in since you only have 1 sec!

:slight_smile:

1 Like

I followed your suggestion and reduced the textSize to 60. I ran the sketch without the Arduino plugged in and nothing happened that I could see. The screen was black. When I plugged in the Arduino, the message
“Searching for satellites . . .”
came up just fine. The message “plug in the Arduino” never appeared but the lprint of “got here” was on the display ???. It seems as though when the Arduino is not plugged in, the text function fails to work. This is not making sense to me.

I did not explore your posted code at great length; I focused on the text not displaying.

The code I posted was a short exploration into this; textSize above 100 did not display for me in setup().

Keep at it!

I have noticed different behavior with P2D and P3D as well; I did not use these in my examples.

I did put the whole serial initialization in a startup() function that can be called from setup() or in draw() until connected. This required a more code and “state” management.
I won’t be sharing this code; it is messy and needs a rework. I am retiring this for now.

Keep exploring this.