SerialPort Write()发送的字节数多于发送缓冲区中的字节数

时间:2013-02-28 08:55:26

标签: c# serial-port modbus crc16

我有一个非常奇怪的问题,我传输一个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, 

任何帮助将不胜感激,以解决此问题,

谢谢

1 个答案:

答案 0 :(得分:1)

我发现了这个问题,

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

非常奇怪,因为原来的modbus slave不会发送大量的0xFF字节。