2014-01-24 9 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'는'LogIncoming' 대신'ReadStoreArray'를 호출하십시오 –

+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 이벤트 연결에 "클래스, 구조체 또는 인터페이스 메서드에 반환 형식이 있어야합니다."라는 메시지가 표시됩니다. 또한 그 말미에 "Identifier expected"가 필요합니다. –

0

당신은 포트에서 동일한 데이터를 두 번 읽을 수 없습니다. 한 번 버퍼에 읽은 다음 버퍼를 공유 (함수 매개 변수로 전달)하거나 복제하여 각 함수에 고유 한 복사본을 제공해야합니다.

2

DataRecieve 처리기 사용에 신경 쓰지 마세요. 정확하지 않습니다. 직렬 포트를 지속적으로 읽고 쓰러지는 모든 바이트를 잡는 스레드를 시작하는 것이 좋습니다.

관련 문제