开发者

How to find the serial ports that are getting response after sending MSG using c#?

The objectve is to find which Serial port is phyisically connected to other machine. I want to Search my system to find the available serial ports and send a test message using all the ports and wait for the respo开发者_JS百科nse. And get the port numbers of Which ever ports get a response is connected to the other machine. How to do?? Thanks.


The SerialPort.GetPortNames() method returns an array of the COM port names of all available serial ports. You could iterate it and try to Open() them. Expect failure, the port might already be opened by another program.

You don't want to send something to a device that doesn't expect it. Using the DsrHolding property is a reasonable test to see if a device is attached that's powered up.

Your ultimate nemesis is going to be the Baudrate property. You cannot guess the proper value. Serial ports are way too primitive to support plug-and-play style device discovery. Avoid using something that cannot work reliably, allow you user to configure your program with the settings you need. It is the normal practice.


Use System.IO.Ports.

public static void OnSerialDataReceived(object sender, 
                                        SerialDataReceivedEventArgs args)
{
  string data = ComPort.ReadExisting();
  Console.Write(data.Replace("\r", "\n"));
}


private static void InitializeComPort(string port, int baud)
{
  ComPort = new SerialPort(port, baud);
  // ComPort.PortName = port;
  // ComPort.BaudRate = baud;
  ComPort.Parity = Parity.None;
  ComPort.StopBits = StopBits.One;
  ComPort.DataBits = 8;
  ComPort.Handshake = Handshake.None;
  ComPort.DataReceived += OnSerialDataReceived;
  ComPort.Open();
}

more on Mark Michaelis' blog


SerialPort.GetPortNames() method is static methods for SerialPort .Do you sure communication between them have flow control?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜