想做一个串口的握手功能,遇到下面的问题:
当baudRateList 只有一个9600时,通讯可以成功;
但当baudRateList 中有多个波特率时,就通讯不上了。
求指教,在线等。
using System.IO.Ports;
public class MySerialPort : SerialPort
{
// public readonly int[] baudRateList = { 9600 };
private readonly int[] baudRateList = { 115200, 57600, 38400, 19200, 9600 };
public string receivedString;
public ManualResetEvent receivedFlag = new ManualResetEvent(false);
public bool HandShake()
{
bool ret = false;
int handShakeLimits = 4;
int retryCount;
foreach (int baudRate in baudRateList)
{
this.BaudRate = baudRate;
this.Close();
this.Open();
this.DiscardInBuffer();
this.DiscardOutBuffer();
this.Write(GetInstructions.serialNum + "\n");
// 等待100毫秒,检查 receivedFlag是否设置为true。如果没有,继续循环
retryCount = 0;
while (!receivedFlag.WaitOne(100))
{
if (retryCount++ >= handShakeLimits)
{
receivedFlag.Reset();
break;
}
}
if (retryCount < handShakeLimits)
{
ret = true;
break;
}
}
return ret;
}
public void GppSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
receivedFlag.Set();
if (sender is SerialPort serialPort)
{
// 将缓冲区回车符前所有内容读取出来
ReceivedString = serialPort.ReadLine();
serialPort.DiscardInBuffer();
serialPort.DiscardOutBuffer();
}
}
}