首页 > 解决方案 > 串口响应缓冲区空问题C#

问题描述

我正在尝试用 C# 制作一个小型控制台程序,该程序模仿硬件,它以主从方式响应特定发送的命令。所以另一个程序(主)将发送一个字节数组,例如:0xFF、0x00、0xCD、0x01、0x00、0x00、0x00;我尝试制作的从控制台程序将检查这个接收到的字节数组,如果它的第三个元素是 0xCD,那么它将响应为 0xFF、0x00、0xCD、0x01、0x00、0x00、0x00。

这是我尝试的整个程序:

using System.IO.Ports;
namespace ConsoleMyConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            SerialPort myPort = new SerialPort();

            byte[] message_to_receive = null;
            byte[] message_to_response = { 0xFF, 0x00, 0xCD, 0x01, 0x00, 0x00, 0x00 };
            myPort.PortName = "COM8";
            myPort.BaudRate = 9600;
            myPort.DataBits = 8;
            myPort.Parity = Parity.None;
            myPort.StopBits = StopBits.One;

            myPort.Open();

            int received_bytes = myPort.BytesToRead;
            myPort.Read(message_to_receive, 0, received_bytes);

            if (message_to_receive[2] == 0xCD)
                myPort.Write(message_to_response, 0, message_to_response.Length);
        }
    }
}

但是当我运行这个程序时,我得到:System.ArgumentNullException: 'Buffer cannot be null错误。我不知道为什么 myPort.Read 会发生这种情况。无论如何,我必须声明 message_to_receive,并且无法使其工作。

标签: c#serial-port

解决方案


请参阅此规范页面。
SerialPort.Read 方法

For the buffer array specified in the parameter of the Read(), an area of the size required by the calling application must be prepared in advance.
Unlike ReadExisting(), ReadLine(), and ReadTo(), the API does not prepare the character string data.

Prepare an array with the longest data size that can occur, or prepare an array with a short size and repeat Read() as many times as necessary.


推荐阅读