c# - 串口响应缓冲区空问题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,并且无法使其工作。
解决方案
请参阅此规范页面。
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.
推荐阅读
- python - 使用 GPIO.RaspberryPi3 上的触发器发送电子邮件
- django - django allauth 设置 EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL 不起作用
- asp.net - 使用 Ninject 进行 Asp.Net Webforms 构造函数注入
- javascript - 如何使用 Javascript 访问带有 innerHTML 的 twig 变量?
- javascript - 焦点选择的 vue.js 元素不是反应式的
- excel - 如何使用每个循环将信息传输到另一个工作表
- html - amp-html:在 amp-list src 中使用查询参数
- angular - 如何在角度 6 中同一组件的多个实例中进行路由
- r - RSelenium - 如何通过单击下一步按钮转到下一页?
- python-3.x - AttributeError:“浮动”对象没有属性“应用”