1
我在VB.NET中創建一個超類型應用程序,並且串行連接有問題。當我向設備發送數據時,我收到了我期待的響應,但在響應中有額外的CR。也就是說,如果我在超級終端中發送命令,我會得到如下響應:串行連接回車
response one
response two
但在我的應用程序它會返回;
response one
response two
代碼如下;
Private Sub textSend_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles textSend.KeyPress
If e.KeyChar = Convert.ToChar(Keys.Enter) Then
connSerial.Write(textSend.Text & vbCr)
textSend.Text = ""
e.Handled = True
End If
End Sub
和
Private Sub connSerial_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles connSerial.DataReceived
ReceivedText(connSerial.ReadExisting())
End Sub
Private Sub ReceivedText(ByVal [text] As String)
If Me.textReply.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
textReply.AppendText([text])
End If
End Sub
我使用的是1200波特率和字面上每行被另一個分隔的,但是如果我起來的波特率爲57600只偶爾發生。即;
response 1
response 2
response 3
response 4
response 5
也許一個額外的換行,而不是,你就必須從字符串中刪除它。使用SerialPort.ReadLine()而不是ReadExisting(),這樣更加高效並且使過濾更容易。包括設置NewLine屬性,所以你必須根本不做任何過濾。 – 2013-02-15 22:23:44