I found that since to many end users in this day and age the serial port is obselete, of course this is not true and it is very important to industrial applications. Some users may become confused when asked to select a “Com Port” they really do not need to be hassled with the choice of COM1, COM2, COM3, etc.

If you are connecting to a device which you can program a response then it is very easy to automatically have the communications port selected. The method is trial and error, each time you send a connect command to the device and see if it replies within 250ms if not then you assume no one was listening and try again on the next port until a response is given.

 The following is an explanation of how to implement this technique in a console application. To integrate this process into a WinForms application as a class will need to be able to create custom events, so follow that section before you attempt this.

 Start VS and create a new console application.

I will assume that you have completed the previous Serial Port tutorials, so you may want to refer to these as you go.

Firstly add the System.IO.Ports; namespace to the top off your new application code. Now declare a serialport called ’sp1′. Then create a static method called “DetectPort”. You should now have the following code:

initial construction of sp_autodetect

In order to control this application we need to add some boolean variables. We will call one of these ‘Lock’ this will be used lock the program inside a loop until a response or a timeout has occured. The other we shall call ‘ConnectionEstablished’ this will be used to prevent the loop restarting once a valid connection is found. These will need to be declared as static so that they are directly accessible from our DetectPort method.

 

More to come soon….Â