c# - 从串行端口读取和存储字节

标签 c# arrays serial-port

我正在尝试创建一个 RS232 应用程序来读取传入数据并将其存储在缓冲区中。我在 RS232 示例中找到了以下代码,但我不确定如何使用它

*RS232 示例 port_DataReceived*

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        if (!comport.IsOpen) return;

        if (CurrentDataMode == DataMode.Text)
        {
            string data = comport.ReadExisting();

            LogIncoming(LogMsgType.Incoming, data + "\n");
        }
        else
        {
            int bytes = comport.BytesToRead;

            byte[] buffer = new byte[bytes];

            comport.Read(buffer, 0, bytes);

            LogIncoming(LogMsgType.Incoming, ByteArrayToHexString(buffer) + "\n");

        }
    }

我正在尝试编写另一种方法,该方法采用传入的字节数组并将其与另一个数组组合......见下文:

private void ReadStoreArray()
{
   //Read response and store in buffer
   int bytes = comport.BytesToRead;
   byte[] respBuffer = new byte[bytes];
   comport.Read(respBuffer, 0, bytes);   

   //I want to take what is in the buffer and combine it with another array
   byte AddOn = {0x01, 0x02}
   byte Combo = {AddOn[1], AddOn[2], respBuffer[0], ...};
}

目前我的代码中有这两种方法,因为我对如何读取传入字节并将其存储到端口感到困惑。我可以在我的“ReadStoreArray”方法中使用“port_DataReceived”方法吗?我需要修改我的“ReadStoreArray”方法吗?还是我应该重新开始?

最佳答案

当您创建 SerialPort 时:

SerialPort comport = new SerialPort("COM1");
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // Shortened and error checking removed for brevity...
    if (!comport.IsOpen) return;
    int bytes = comport.BytesToRead;
    byte[] buffer = new byte[bytes];
    comport.Read(buffer, 0, bytes);
    HandleSerialData(buffer);
}

//private void ReadStoreArray(byte[] respBuffer)
private void HandleSerialData(byte[] respBuffer)
{
   //I want to take what is in the buffer and combine it with another array
   byte [] AddOn = {0x01, 0x02}
   byte [] Combo = {AddOn[1], AddOn[2], respBuffer[0], ...};
}

关于c# - 从串行端口读取和存储字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21337123/

相关文章:

c# - 获取实例类的父类

c# - 从 "External"方法更新 ShowMessageAsync 进度值

c# - 无法使用带有 Visual Studio 2015 的 IIS Express 调试 ASP.NET 5

c - 如何在C头文件中分配特定的数组大小

PHP 交易扩展蜡烛识别错误

c# - UnityWebRequest.downloadHandler 返回 null,同时从 Node 服务器获取响应

MySQL Where IN 数组

python - 如何使用 Zoom 7.2m 三频 USB 调制解调器通过 AT 命令发送短信?

c# - 使用 .NET 框架读取串口的正确方法是什么?

linux - 嗅探IOCTL和串口通信