C# 串口通信握手与数据读取代码优化
private void ReadWriter()
{
string handshake = "?"; // 握手信号
string received = ""; // 接收到的数据
int count = 0; // 发送次数计数器
// 发送握手信号
serialPort.Write(handshake);
// 循环等待接收数据
while (count < 50)
{
// 暂停50毫秒
System.Threading.Thread.Sleep(50);
try
{
// 读取数据
received += serialPort.ReadExisting();
}
catch (Exception ex)
{
Send(ex.Message);
return;
}
// 判断是否握手成功
if (received.Contains("."))
{
// 发送T信号
for (int i = 0; i < 24; i++)
{
serialPort.Write("T");
System.Threading.Thread.Sleep(3);
}
// 暂停50毫秒
System.Threading.Thread.Sleep(50);
if (serialPort.BytesToRead >= 15)
{
byte[] butt2 = new byte[1024];
int len = serialPort.Read(butt2, 0, serialPort.BytesToRead);
string str = Encoding.Default.GetString(butt2, 0, len);
string match = arr.FirstOrDefault(x => str.IndexOf(x.ToString().Length == 3 ? "0" + x.ToString() : x.ToString()) >= 0);
if (match == null)
{
Send("功率波长错误,目前功率计,计算值的波长是:" + string.Join(",", arr.ToArray()) + ",请检查你的功率计波长是否正确,波长正确但未包含在目前计算的波长里,如果连续是这样,请联内网通联系蒋云开。");
}
else
{
int index = str.IndexOf(match);
if (index >= 5)
{
str = str.Substring(0, index == 0 ? str.Length - 0 : index);
switch (str[str.Length - 1])
{
case '2':
str = Replace(str.Insert(7 - 1, "."));
Send(str);
break;
case '3':
str = Replace(str.Insert(7 - 2, "."));
Send(str);
break;
case '4':
str = Replace(str.Insert(7 - 3, "."));
Send(str);
break;
case '5':
str = Replace(str.Insert(7 - 4, "."));
Send(str);
break;
}
if (str.Length > 9)
{
Send("功率波长错误,目前功率计,计算值的波长是:" + string.Join(",", arr.ToArray()) + ",请检查你的功率计波长是否正确,波长正确但未包含在目前计算的波长里,如果连续是这样,请联内网通联系蒋云开。");
}
serialPort.Write("HO");
return;
}
}
}
else
{
// 继续发送握手信号
serialPort.Write(handshake);
count++;
}
}
}
Send("握手失败。");
}
原文地址: http://www.cveoy.top/t/topic/jGN9 著作权归作者所有。请勿转载和采集!