C# 枚举串口
Byte DataRecTemp = 0;
Byte[] DataTest = new Byte[1];
int DataCount = 0;
string[] ports = System.IO.Ports.SerialPort.GetPortNames();
foreach(string port in ports){
serialPort.PortName = port;
serialPort.BaudRate = 9600;
MessageBox.Show(port);
try
{
serialPort.Open();
if (serialPort.IsOpen)
{
DataTest[0] = 0xFF;
serialPort.Write(DataTest, 0, 1);
while (DataCount < 5)
{
DataRecTemp = Convert.ToByte(serialPort.ReadByte());
if (DataRecTemp == 0x55)
{
DataCount++;
}
else
{
break;
}
}
if (DataCount == 5)
{
MessageBox.Show("可行");
break;
}
else
{
MessageBox.Show("不可行");
serialPort.Close();
}
}
}
catch
{
MessageBox.Show("未知错误!");
}
}
MessageBox.Show("可行"); 无法执行到,为什么呢?
含笑半步颠
10 years, 6 months ago