2013-04-02 48 views
1

我試圖建立到另一臺機器的串行連接。我正在使用虛擬串行端口模擬器來嘗試此操作。我在超級終端上使用的設置如下所示。我可以看到portopen是true,但我無法檢查我是否可以寫入或讀取。當我嘗試使用ReadLine方法時,它給出TimeoutException,並且當它是readExisting命令時,它什麼也不做。永遠不會觸發DataReceived。你能幫我解決嗎?串行端口連接,Readline/ReadExisting不起作用

private void Page1_Load(object sender, EventArgs e) 
     { 

     //Port name can be identified by checking the ports 


     // section in Device Manager after connecting your device 
     serialPort1.PortName = "COM14"; // that one works for me 

     //Provide the name of port to which device is connected 

     //default values of hardware[check with device specification document] 
     serialPort1.BaudRate = 115200; 
     serialPort1.Parity = Parity.None; 
     serialPort1.DataBits = 8; 
     serialPort1.StopBits = StopBits.One; 
     serialPort1.Handshake = Handshake.None; 
     serialPort1.RtsEnable = true; 
     serialPort1.DtrEnable = true; 
     serialPort1.ReceivedBytesThreshold = 8; 
     serialPort1.ReadTimeout = 2000; 
     serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); // 
     // Writes data to the Serial Port output buffer 

     //opens the port 
     serialPort1.Open(); 
    } 

     private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 


     inputData = serialPort1.ReadExisting(); 
     this.Invoke((MethodInvoker)delegate { DoUpdate(); }); 


    } 

    public void DoUpdate() 
    { 
     textOutput.Text = (textOutput.Text + inputData); 

    } 

    private void btnReadExist_Click(object sender, EventArgs e) 
    { 

     if ((serialPort1.IsOpen == true)) 
     { 


      serialPort1.WriteLine("something"); 
      string read= serialPort1.ReadExisting(); 
      //string output = serialPort1.ReadLine(); 
      textOutput.Text += read; 

     } 
    } 


    private void Page1_FormClosed(object sender,System.Windows.Forms.FormClosedEventArgs e) 
    { 
     // Close the Serial Port 
      serialPort1.Close(); 
    } 
+0

當你說** COM14 **「適合我」你是什麼意思?你的意思是它只是連接成功或你** **知道**是模擬器運行的端口?你可以連接到別的東西而不是模擬器? – Belogix

+0

在使用模擬器時,我使用了其他端口併成功連接。我的意思是,當連接到實際設備時,使用COM14時連接成功。 –

回答

0

問題似乎是你正在閱讀兩個代碼塊:第一,直接在按鈕的事件發送文本後。其次你有一個事件分配,當異步調用時讀取數據。你應該決定使用哪一個並移除另一個。

+0

當我刪除DataReceived事件時它也不起作用。我已經使用writeline(以後也寫入方法)和redexisting。我可以看到我寫入SerialConnection的文本嗎? –