SerialPort Write()发送的字节数超过发送缓冲区

本文关键字:缓冲区 字节数 Write SerialPort | 更新日期: 2023-09-27 18:01:43

我有一个非常奇怪的问题,我发送一个105字节的[]缓冲区,并不断接收 116字节的另一边。

原始数据的最后2字节为CRC16

我用来传输的代码是,它永远循环。

    static SerialPort sp = null;
    static void Main(string[] args)
    {
         //105 bytes send buffer
        byte[] data = new byte[] {0xa,0x03,0x64,0x0e,0x15,0x00,0x01,0x00,
                                  0x01,0x00,0x06,0x00,0x23,0x00,0x5f,0x00,
                                  0x00,0x00,0x00,0x00,0x7c,0x00,0x00,0x00,
                                  0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
                                  0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,
                                  0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,
                                  0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
                                  0x00,0x00,0x00,0x25,0xb8,0x00,0x05,0xff,
                                  0x23,0x00,0x00,0x00,0x00,0x00,0xa2,0x00,
                                  0x00,0x02,0x20,0x00,0x04,0x00,0x03,0x00,
                                  0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
                                  0x01,0x00,0x00,0x00,0x01,0x00,0x1f,0x00,
                                  0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xae,
                                  0x1f
        };
        Console.WriteLine("Serial Port Test");
        sp = new SerialPort("COM1", 19200);
        sp.Open();
        if (sp.IsOpen)
        {
            Console.WriteLine("Begining to transmit serial data..");
        }
        for (; ; )
        {
            Thread.Sleep(1000);
            sp.Write(data,0,data.Length);
            sp.DiscardOutBuffer();
        }
        Console.WriteLine("End of transmission");
        Console.ReadKey();
    }

我经常在另一边得到的是以下116字节(消息以原始的CRC字节结束是多么奇怪??)

0xa, 0x03, 0x64, 0x0e, 0x15, 0x00, 0x01, 0x00,
0x01, 0x00, 0x06, 0x00, 0x23, 0x00, 0x5f, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x25, 0xb8, 0x00,
0x05, 0xff, 0xff, 0x23, 0x00, 0x00, 0x00, 0x00,
0x00, 0xa2, 0x00, 0x00, 0x02, 0x20, 0x00, 0x04,
0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xae, 0x1f, 

任何帮助将感激解决这个问题,

谢谢

SerialPort Write()发送的字节数超过发送缓冲区

我发现问题了,

似乎在Tibbo模块上启用了"带内命令"设置,禁用它后,它停止用额外的0xFF字节"填充"0xFF字节。

非常奇怪,因为它不会对发送大量0xFF字节的原始modbus slave执行此操作。