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

时间:2014-01-24 16:02:53

标签: 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”方法?或者我应该重新开始?

3 个答案:

答案 0 :(得分:7)

创建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], ...};
}

答案 1 :(得分:2)

不要使用DataRecieve处理程序,它非常不准确,你最好开始一个不断读取串口并抓住每个字节的线程。< / p>

答案 2 :(得分:0)

您无法从端口读取相同的数据两次。您需要将其读入缓冲区一次,然后共享缓冲区(作为函数参数传递)或克隆它以为每个函数提供自己的副本。