Martin Gabriel
Martin Gabriel

Reputation: 59

How to autodetect connection of serial COM port c#

I have application to communication with device. Device is connected through serial COM port. My app can comunicate with device.

I need some method / event, that can scan COM ports through running app. When I'll connect device to PC - method / event will print MessageBox with message "connected", or something like that.

I found something like this:

comPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

But it doesnt work.

Upvotes: 2

Views: 11504

Answers (1)

Mike Dinescu
Mike Dinescu

Reputation: 55750

I'm not sure if you are trying to auto-detect which port a device is connected to, or auto-detect whether a device is connected to a specific port.

In both cases though, the principle is the same:

  1. you enumerate the the serial ports using: SerialPort.GetPortNames if you need to determine the port, or skip to the Step 2 if you already know the port
  2. for each port in the collection you open a connection by creating a new SerialPort object for it, and by calling Open
  3. for each open connection you attempt to write/read from the port the sequence of data that determines whether your device is attached
  4. for each open connection if the data read times out then there is no device attached to the port; otherwise, if you get back what you expect you know your device is attached
  5. for each port, close the connection using Close on the SerialPort object.

Performing the above at any given point will tell you whether your device is attached at that point, and which port it is attached to.

If you need to do presence detection continuously, then you will probably want to create a timer and perform this test periodically (every 30 seconds, or every 2 minutes - depending on the latency you are willing to accept).

NOTE

As others have indicated in the answers, you will want to run the serial port detection code asynchronously so as not to block your main application while scanning the ports. The scanning is guaranteed to take a while because of the time-outs of the ports that have no device attached.

Upvotes: 10

Related Questions