automatically detect USB port with arduino from the computer

Hi, I need to discover the port number where arduino is connected to. I can use many languages like c++, java, processing but I need to autodetect the port in windows and osX. I have tried to use 'processing' and to scan all the available ports but when I speak to some busy port an exception arises. Do you know how can I solve this problem? Is it possible to obtain the device name in any program language? (I know it's in c# but only under windows). Thanks in advance for your help

Do you know how can I solve this problem?

Use try/catch and catch the exception.

Is it possible to obtain the device name in any program language?

If it is possible in one, it is possible in all. Exactly how is dependent on the language.

Thanks for the answer
Using try and catch the program exits badly… This is the code:

        try{
        arduinoPort = new Serial(this, Serial.list()[i], 9600) ;      // Open 1st port in list

       
      } 
        catch (Exception e)
      {
        System.out.println("exc");
        portaDisponibile=false;
        arduinoPort.stop();
      }

On the debug screen it is written:

gnu.io.PortInUseException: Unknown Application
at gnu.io.CommPortIdentifier.open(CommPortIdentifier.java:467)
at processing.serial.Serial.(Unknown Source)
at processing.serial.Serial.(Unknown Source)
at rilevaSeriale.setup(rilevaSeriale.java:59)
exc
at processing.core.PApplet.handleDraw(Unknown Source)
at processing.core.PApplet.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)

and at the end quitting the program:
Error 0x5

It is for this that I prefer to search for the right com using the device name and not try to handshake all of them

        catch (Exception e)
gnu.io.PortInUseException: Unknown Application

A PortInUseException is not necessarily a Exception.

It is for this that I prefer to search for the right com using the device name

Using what device name?

PaulS: A PortInUseException is not necessarily a Exception.

what do you mean?

Using what device name?

For example if go to control panel->system->devices I can find that my arduino is called as "arduino leonardo" by windows. The information is stored on the system register so may be I have to find a way to ask it from my code. I have no idea for osX

what do you mean?

You have registered to catch exceptions of type Exception. If PortInUseException is not derived from Exception, you can't catch it. Wrong kind of net.

Hello,

I am not 100% sure what your intended application is. But, I have had success in doing what you seek through the use of Visual Basics 2010. The Try/Catch functions work very well in VB 2010.

Another suggestion, you could have a on-board code that 'handshakes' with the program you designed. However, I don't think this would overcome your immediate problem of occupied Ports.

I hope I helped somewhat,

Good luck,

I've seen this work in Processing. println(Arduino.list());

I was surprised to find that arduino = new Arduino(this, Arduino.list()[0], 57600); would need '0' to work. Two other ports are working and the Arduino-port is Port8. Ehmee .. maybe that's why my setup /doesn't/ work ..

See the extensive code I posted in http://arduino.cc/forum/index.php/topic,115580.0.html for a workable visual-basic solution.

I've seen this work in Processing. println(Arduino.list());

Because println() is overloaded to take a list.

I was surprised to find that arduino = new Arduino(this, Arduino.list()[0], 57600); would need '0' to work.

Why? The function's second argument is an item, not a list. The [ 0 ] part says which item from the list.

the problem is that with arduino.list() I obtain all the serial devices connected to my computer. I think for ddetecting arduino I must use a sort of handshake. The problem is that I need to listen to all the devices connected but if they are already busy (the com port is occcupied) an exception occours and from processing it seems not possible to catch the "PortInUseException". Any other suggestion to detect the port number with my arduino?

(PS: thanks to everyone that is giving me good advices to solve this problem!)

cantore: the problem is that with arduino.list() I obtain all the serial devices connected to my computer.

Wouldn't that solve your problem? You can scrutinize each member-name in the list and have the index of the port you find.

I think for ddetecting arduino I must use a sort of handshake.

A handshake are sometimes used as part of a start-communication and sometimes fixed by a formal protocol used. If you'r in a position to use a successful handshake, you've already found your port. But, ok, I see where you'r going. I'm not sure of what functions are available, but the set I used in vb needed an eqvivalent to serial.start() before any communication. If you can assume, that your board is in a closed state ... if it's got a isOpen() .. I don't know.

The problem is that I need to listen to all the devices connected but if they are already busy (the com port is occcupied) an exception occours and from processing it seems not possible to catch the "PortInUseException". Any other suggestion to detect the port number with my arduino?

Well .. you can still set up a catch/try block ... but that way round may bring you to where your teachers told you not to go.

Paul, you sure can catch me in the shortcomings of my expressions. I'm surprised that I get a sort of 'passed the array-limit' error on [2] when there are three available ports, that the third (arduino) on the list is available on [1] and that accessing [0] throws no error ... but how could you know ..

Carsten53T: You can scrutinize each member-name in the list and have the index of the port you find.

Can you suggest me how to do this please? This was the fist way I have tried to implement but I did not found any way to obtain the com devices names in both windows and osx (for example in windows is easy with C#, but this is another job...)

Check out Processing … in modes/java/libraries/arduino/examples/arduino_output

void setup() {
  size(470, 200);
  
  println(Arduino.list());
  arduino = new Arduino(this, Arduino.list()[0], 57600);

On my pc println(Arduino.list()); prints the name (“Port8”) of one (a port with an arduino attached) out of three ports. Outside println() Arduino.list() should be accessible for tabbing through … right?

EDIT:
I completely forgot that it’s a downloaded library
Look/get at it at
http://www.arduino.cc/playground/interfacing/processing

thanks Carsten53T, but the problem is that you obtain the name of the port, not of the device. So if I have 3 com busy, for example COM3 COM8 and COM10 it is not possible to automatically detect on wich one arduino is connected to.(of course if I know the port becouse I saw it from my OS I can set it manually but this is not what I need to do)

cantore: thanks Carsten53T, but the problem is that you obtain the name of the port, not of the device. So if I have 3 com busy, for example COM3 COM8 and COM10 it is not possible to automatically detect on wich one arduino is connected to.(of course if I know the port becouse I saw it from my OS I can set it manually but this is not what I need to do)

cantore, That's as far as I can take you. The first time I attach a board to my pc .. I'll have to go through the procedure of finding the proper driver and 'install' it to the board. At that time, the board will be blessed with a port-name that appears to stick to that particular board and not the usb-port that it is connected to. I think that it'll be a mess to automate catching this portname as it would need an app running prior to the time you choose to connect a new board. Even the ardino-editor doesn't do an automatic search .. atleast you may often find yourself have to choose which port to use. You can mimic that with gui in processing (make it show a drop-down list with available ports). I'm way too inexperienced to suggest what's available if you choose to look at 'port-methods' in c/c++. Remember to pop a message if you succeed .. it would be a nice thing to master ..

I have done this successfully using Visual Studio Basic.

VB Code sends a "4" to all com ports in a loop test. Arduino code on boot looks for a "4" at the serial port. When it reads a "4" it sends back a "4" to confirm you have found the correct serial port.

Arduino code:

int x = 2; void setup() { // initialize serial: Serial.begin(9600); Serial.flush(); Serial.write (4) ; pinMode(10,OUTPUT); pinMode(11,OUTPUT); pinMode(12,OUTPUT); pinMode(13,OUTPUT);

digitalWrite(10,LOW); digitalWrite(11,LOW); digitalWrite(12,LOW); digitalWrite(13,LOW); Serial.flush(); }

void loop() { // send data only when you receive data:

while (Serial.available()==0); int Incomming = Serial.read()-'0'; if (Incomming == 4){ delay (20) ; Serial.write (4) ; }


VB Code:

Imports System.IO Imports System.IO.Ports Imports System.Threading

Public Class Form1 Dim Serialport1 As SerialPort Dim ArduinoPort As SerialPort Dim Exists As Byte = 0 Dim Message As String Dim ArdCOM As String Dim InButtonPressed As Boolean Dim OutButtonPressed As Boolean Dim ButtonIn As Boolean Dim ButtonOut As Boolean Dim CanLoopGo As Boolean = False Dim Direction As Integer = 0 Dim CNT As Integer = 0 Dim Start As Integer Dim Finish As Integer

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

For Each sp As String In My.Computer.Ports.SerialPortNames TextBox1.Text = " " + (sp) + " Found" & Environment.NewLine Serialport1 = New SerialPort(sp) Serialport1.Open() Show() 'Serialport1.ReadChar() Serialport1.Write("4") Delay(2) Serialport1.Write("4") TextBox1.Text = TextBox1.Text + " Diagnostic tests: OK" Serialport1.ReadTimeout = 500 Try Message = Serialport1.ReadChar() TextBox1.Text = TextBox1.Text + " " & Environment.NewLine + " Serial Read: " + " " + Message & Environment.NewLine & Environment.NewLine If Message.Contains("4") Then ArduinoPort = Serialport1 Exists = 1 TextBox1.Text = TextBox1.Text + ("NinoFocus found: ") + (sp) End If Catch generatedExceptionName As TimeoutException

End Try Next If Exists = 0 Then TextBox1.Text = ("No Focuser found.") Button2.Enabled = False Button3.Enabled = False End If

' Calls

End Sub


VB Form looks like this:

Simple form with a * multiline text box called Textbox1 * 3 buttons called Button1, Button2 and Button3

That's it!

Nino

You must add a Try/Catch also here
Serialport1.Open()
because if a Serial Port is in use you get an error.