简体   繁体   English

串口响应缓冲区 null 问题 C#

[英]Serial port responder buffer null issue C#

I am trying to make a small Console program in C# which mimics a hardware where the it responses a particular sent command in a master slave fashion.我正在尝试在 C# 中制作一个小型控制台程序,该程序模仿硬件,它以主从方式响应特定发送的命令。 So another program(master) will send a byte array for example: 0xFF, 0x00, 0xCD, 0x01, 0x00, 0x00, 0x00;所以另一个程序(主)将发送一个字节数组,例如:0xFF、0x00、0xCD、0x01、0x00、0x00、0x00; and the slave Console program I try to make will check this received byte array and if its third element is 0xCD then it will respond as 0xFF, 0x00, 0xCD, 0x01, 0x00, 0x00, 0x00.我尝试制作的从控制台程序将检查这个接收到的字节数组,如果它的第三个元素是 0xCD,那么它将响应为 0xFF、0x00、0xCD、0x01、0x00、0x00、0x00。

Here is the entire program I tried:这是我尝试的整个程序:

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

But when I run this program I get: System.ArgumentNullException: 'Buffer cannot be null error.但是当我运行这个程序时,我得到: System.ArgumentNullException: 'Buffer cannot be null错误。 I dont know why is this happening at myPort.Read.我不知道为什么 myPort.Read 会发生这种情况。 I have to declare message_to_receive anyway, and couldn't make it work.无论如何,我必须声明 message_to_receive,并且无法使其工作。

See this specification page.请参阅此规范页面。
SerialPort.Read Method 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.对于Read() 的参数中指定的缓冲区数组,必须提前准备调用应用程序所需大小的区域。
Unlike ReadExisting(), ReadLine(), and ReadTo(), the API does not prepare the character string data.与 ReadExisting()、ReadLine() 和 ReadTo() 不同,API 不准备字符串数据。

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.准备一个可能出现的最长数据大小的数组,或者准备一个较短的数组并根据需要多次重复 Read()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM