2014-01-24 79 views
4

我正在尝试创建一个读取传入数据并将其存储在缓冲区中的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”方法吗?或者我应该重新开始?

+0

第一个函数是一个事件处理函数:http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived(v=vs.110).aspx。当您将事件添加到端口时,它会自动调用。让'port_DataReceived'调用'ReadStoreArray'而不是'LogIncoming' –

+0

您需要记住,您可能无法在一个事件处理程序中接收到您的整个消息。你需要阅读,直到你得到你需要的字节数。 –

+0

感谢您的回复。在大多数情况下,我想按原样离开事件处理程序。我只想将响应与上述“ReadStoreArray”中提到的特定方法的另一个数组结合使用。我将如何将读入“缓冲区”的字节放入我的“ReadStoreArray”方法中? – Nevets

回答

5

当您创建的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], ...}; 
} 
+0

'ReadStoreArray'不再是不读取函数的好名字,也是那些本地人应该是数组的? –

+0

是的,我复制并粘贴。将修复..... –

+0

在DataReceived事件的挂钩中,我得到“类,结构或接口方法必须具有返回类型”;还有“预期标识符”。 –

0

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

2

不用担心使用DataRecieve处理程序,它是非常不准确的,您最好启动一个不断读取串行端口并抓取每个字节的线程。