1
votes

I'm creating a Hyperterminal type app in VB.NET and have a problem with the serial connection. When I send data to the device, I get the response I'm expecting but with an extra CR in the response. Ie if I send a command in Hyperterminal I get a response such as;

response one
response two

But in my app it will return;

response one

response two

The code is as follows;

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

and

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

I am using a 1200 baud rate and literally every line is seperated by another, however if I up the baud rate to 57600 it only happens occasionally. Ie;

response 1
response 2
response 3

response 4
response 5
1
Probably an extra linefeed instead, you'll have to remove it from the string. Use SerialPort.ReadLine() instead of ReadExisting(), that's both a lot more efficient and makes the filtering easier. Including setting the NewLine property so you have to do no filtering at all. - Hans Passant

1 Answers

0
votes

You can use the WriteLine Method instead of Write Method

   If e.KeyChar = Convert.ToChar(Keys.Enter) Then 
        connSerial.WriteLine(textSend.Text & vbCr)
        textSend.Clear();
        e.Handled = True 
   End If