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 "";
}

注释:

  1. using System.IO.Ports; 引入串口命名空间。

  2. public static string Handshake(SerialPort port) 定义方法,传入一个串口对象。

  3. string response = ""; 定义一个空字符串,用于存储串口返回的数据。

  4. int count = 0; 定义计数器,用于记录握手次数。

  5. port.Write("?"); 发送 '?' 握手。

  6. while (count < 50) 循环 50 次。

  7. System.Threading.Thread.Sleep(20); 每隔 20 毫秒等待串口缓冲区有数据。

  8. response += port.ReadExisting(); 读取串口缓冲区的数据并追加到 response 中。

  9. if (response.Contains(".")) 如果返回 '.' 表示成功握手,返回 '.'

  10. count++; 计数器加 1。

  11. if (!response.Contains(".")) 如果连续 50 次没有返回 '.', 退出。

  12. for (int i = 0; i < 24; i++) 循环 24 次。

  13. port.Write("T"); 发送 'T'。

  14. System.Threading.Thread.Sleep(3); 每隔 3 毫秒等待串口缓冲区有数据。

  15. response += port.ReadExisting(); 读取串口缓冲区的数据并追加到 response 中。

  16. if (response.Length >= 24) 如果接收的字符大于等于 24,返回 '.'

  17. return ""; 如果没有返回 '.', 返回空字符串。

C# 串口握手和数据发送方法 - 完整代码示例

原文地址: https://www.cveoy.top/t/topic/jGpF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录