简体   繁体   中英

receive data from serial port using VB.NET, encoding pb?

In VB.NET I try to communicate with a device on a serial port, here is the result expected :

ASCII (the device answer correctly) :

在此处输入图片说明

< ABC000 > is sent each second to maintain the communication.

in Hexa ( OKAY) :

在此处输入图片说明

What I tried :

Public myComPort As New SerialPort
...
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
   For Each portname As String In My.Computer.Ports.SerialPortNames

        myComPort.PortName = portname
        myComPort.BaudRate = 4800
        myComPort.Parity = Parity.None
        myComPort.DataBits = 8
        myComPort.StopBits = StopBits.One
        myComPort.ReadTimeout = 5000
        myComPort.WriteTimeout = 2000

        myComPort.Open()

        AddHandler myComPort.DataReceived, SerialDataReceivedEventHandler

        aTimer.Enabled = True
    Next
End sub

' Define a delegate class to handle DataReceived events.
Friend Delegate Sub SerialDataReceivedEventHandlerDelegate(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)

' Create an instance of the delegate.
Private SerialDataReceivedEventHandler As New SerialDataReceivedEventHandler(AddressOf DataReceived)

Friend Sub DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)

   Dim bytesNber As Integer = myComPort.BytesToRead
   Dim hex As String = ""
   Dim hex2 As String = ""
   Dim str As String = ""
   Do
        Dim ReceiveBuf() As Byte = New Byte() {}
        Array.Resize(ReceiveBuf, bytesNber)
        myComPort.Read(ReceiveBuf, 0, bytesNber)

        str &= Bytes_To_String2(ReceiveBuf)
        hex &= HexToString(str)
        hex2 &= bytetohex(ReceiveBuf)

  Loop While myComPort.BytesToRead <> 0

  WriteLog("test1:" & str)
  WriteLog("test2:" & hex)
  WriteLog("test2b:" & hex2)
  WriteLog("test3:" & HexToString(str))
End Sub

'---------------------------------------------------------
Private Function Bytes_To_String2(ByVal bytes_Input As Byte()) As String
    Dim strTemp As New StringBuilder(bytes_Input.Length * 2)
    For Each b As Byte In bytes_Input
        strTemp.Append(Conversion.Hex(b))
    Next
    Return strTemp.ToString()
End Function

Function HexToString(ByVal hex As String) As String
    Dim text As New System.Text.StringBuilder(hex.Length \ 2)
    For i As Integer = 0 To hex.Length - 2 Step 2
        text.Append(Chr(Convert.ToByte(hex.Substring(i, 2), 16)))
    Next
    Return text.ToString
End Function

Public Function bytetohex(buffer() As Byte) As String
    bytetohex = vbNullString
    For i = 0 To UBound(buffer)
        bytetohex = bytetohex & Hex(buffer(i))
    Next i
End Function
'---------------------------------------------------------

Timer to maintain the communication:

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Create a timer and set a one second interval.
    aTimer = New System.Timers.Timer()
    aTimer.Interval = 900

    ' Hook up the Elapsed event for the timer.  
    AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
End Sub
Private Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs)

  BeginInvoke(Sub()
                  WriteLog("ABC000")
                  myComPort.WriteLine("ABC000")
              End Sub)
End Sub

But what I get :

在此处输入图片说明

I also tried:

myComPort.Encoding = System.Text.Encoding.ASCII

with :

  Friend Sub DataReceived (...)
      txtDataReceived.Invoke(New myDelegate(AddressOf updateTextBox), New Object() {})
 End Sub
 Public Sub updateTextBox()
    txtDataReceived.AppendText(myComPort.ReadExisting)
End Sub

result :

在此处输入图片说明

Any idea?

In your DataReceived function, instead of this:

Dim ReceiveBuf() As Byte = New Byte() {}
Array.Resize(ReceiveBuf, bytesNber)
myComPort.Read(ReceiveBuf, 0, bytesNber)

str &= Bytes_To_String2(ReceiveBuf)

do this:

str = myComPort.ReadExisting()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM