简体   繁体   中英

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 response. 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()方法是SerialPort的静态方法。您确定它们之间的通信具有流控制吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM