2011-07-07 54 views
0

我有一個應用程序從COM端口讀取數據,然後對它接收到的數據進行處理。我目前正在使用一個COM端口仿真器(因爲我沒有設備可供我使用),但我給它提供了一個數據樣本。如果我在開始傳輸數據之前打開COMPort,該程序似乎可以很好地工作。但是,如果我在打開COMPort之前開始傳輸,然後打開端口,則dataReceived事件永遠不會被觸發,並且我永遠無法獲取任何數據。我甚至在打開端口時嘗試刷新INBuffer,但無法讀取它。當端口已經流式傳輸時COM端口出錯

我的代碼來打開的端口是這樣的:

public void setupComPort(string baudRate, string dataBits, string stopBits, string parity, string portName) 
    { 
     if (comPort.IsOpen) 
      comPort.Close(); 
     comPort.BaudRate = int.Parse(baudRate); 
     comPort.DataBits = int.Parse(dataBits); 
     comPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBits); 
     comPort.Parity = (Parity)Enum.Parse(typeof(Parity), parity); 
     comPort.PortName = portName; 
     // When data is recieved through the port, call this method 
     comPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); 
     try 
     { 
      // Open the port 
      comPort.Open(); 
      //If there's data in buffer, discard so we can start receiving 
      //comPort.DiscardInBuffer(); 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show(e.Message, "Error Opening Port", MessageBoxButton.OK, MessageBoxImage.Error); 
     } 
    } 

任何幫助,將不勝感激。

+0

我很困惑,'如果我在打開COMPORT之前開始傳輸,那麼dataReceived事件永遠不會被觸發';它不應該打開COM端口。 – SwDevMan81

+0

我的意思是我開始傳送信息,然後我設置了端口。那有意義嗎?我會編輯我的問題來澄清。 – avivas

+0

啊,好吧,是的,這是有道理的。這可能是模擬器的問題... – SwDevMan81

回答

0

它可能是模擬器的問題。我猜想當你擁有實際的硬件時,問題就會消失。我唯一能想到的其他事情就是將ReceivedBytesThreshold設置爲默認設置(比如10或者其他)。

+0

嘗試了這種方法,仍然沒有奏效。 – avivas

+0

我使用Com0Com來創建虛擬端口,這是什麼導致了這個問題。我必須更改端口設置並啓用緩衝區溢出設置,現在無論在打開端口之前何時流式傳輸數據,我都可以獲取數據。 – avivas