C# 串口握手和数据发送方法 - 完整代码示例
using System.IO.Ports;
public static string Handshake(SerialPort port)
{
string response = "";
int count = 0;
// 发送 '?' 握手
port.Write("?");
// 每隔 20 毫秒读取一次串口缓冲区
while (count < 50)
{
System.Threading.Thread.Sleep(20);
response += port.ReadExisting();
if (response.Contains("."))
{
// 如果返回 '.' 表示成功握手
return ".";
}
count++;
}
// 连续 50 次没有返回 '.', 退出
if (!response.Contains("."))
{
return "";
}
// 发送 24 次 'T'
for (int i = 0; i < 24; i++)
{
port.Write("T");
System.Threading.Thread.Sleep(3);
response += port.ReadExisting();
if (response.Length >= 24)
{
// 接收的字符大于等于 24,返回
return ".";
}
}
return "";
}
注释:
-
using System.IO.Ports;引入串口命名空间。 -
public static string Handshake(SerialPort port)定义方法,传入一个串口对象。 -
string response = "";定义一个空字符串,用于存储串口返回的数据。 -
int count = 0;定义计数器,用于记录握手次数。 -
port.Write("?");发送 '?' 握手。 -
while (count < 50)循环 50 次。 -
System.Threading.Thread.Sleep(20);每隔 20 毫秒等待串口缓冲区有数据。 -
response += port.ReadExisting();读取串口缓冲区的数据并追加到 response 中。 -
if (response.Contains("."))如果返回 '.' 表示成功握手,返回 '.' -
count++;计数器加 1。 -
if (!response.Contains("."))如果连续 50 次没有返回 '.', 退出。 -
for (int i = 0; i < 24; i++)循环 24 次。 -
port.Write("T");发送 'T'。 -
System.Threading.Thread.Sleep(3);每隔 3 毫秒等待串口缓冲区有数据。 -
response += port.ReadExisting();读取串口缓冲区的数据并追加到 response 中。 -
if (response.Length >= 24)如果接收的字符大于等于 24,返回 '.' -
return "";如果没有返回 '.', 返回空字符串。
原文地址: https://www.cveoy.top/t/topic/jGpF 著作权归作者所有。请勿转载和采集!