I'm communicating over a serial port to a piece of equipment which needs to receive the data in Hex format. Recently, a requirement came up to not only send the commands, but receive responses and parse them. I have been successfully sending commands for some time, and I am able to capture the response, but cannot decode it to something which can be used further.
Here is the code currently in use:
In the HexToStr function, the first time it gets to the text.append line, it throws an error that it "Could not find any recognizable digits."
How can I translate the data back into a string I can parse?
Cheryl dc Kern
Here is the code currently in use:
Code:
Public Function SendCom(ByVal strCommand As String, ByVal COMport As String)
Dim RetVal
Dim BS As New IO.Ports.SerialPort
Try
BS.PortName = COMport 'sets the COM port based on the setting on the main form
BS.BaudRate = 9600
BS.StopBits = IO.Ports.StopBits.One
BS.DataBits = 8
BS.Parity = IO.Ports.Parity.None
BS.Encoding = System.Text.Encoding.GetEncoding(1252)
BS.Handshake = Ports.Handshake.RequestToSendXOnXOff
If BS.IsOpen = False Then
BS.Open()
End If
BS.Write(strCommand)
Threading.Thread.Sleep(20)
BS.ReadTimeout = 100
RetVal = BS.ReadExisting
BS.Close()
RetVal = HexToStr(RetVal)
Return RetVal
Catch ex As TimeoutException
MsgBox(ex.Message)
Return "FAIL"
End Try
End Function
Function HexToStr(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
In the HexToStr function, the first time it gets to the text.append line, it throws an error that it "Could not find any recognizable digits."
How can I translate the data back into a string I can parse?
Cheryl dc Kern