'Send Array of Bytes to serial port
I'm am struggeling with the following issue. I need to send multiple Bytes to a serial port. Seems pretty easy and I don't know if I have tomatoes on my eyes, but I can't get it to work. Sending single bytes is working fine, generating an array manually with multiple Hex-values as bytes works fine too. But converting a String to an array of bytes doesn't work.
Here is my simplyfied code:
send(ByVal sCommand as String, ByVal sComPort as String, ByRef sRetStr as String, ByVal lTimeout as long)
Dim lStopWatch as Stopwatch
lStopWatch.Reset()
lStopWatch.Restart()
sRetStr = ""
'In this example sCommand contains "UJB3A01019221043"
Try
comObject as System.IO.Ports.SerialPort = New System.IO.Ports.SerialPort
comObject.PortName = sComport
comObject.BaudRate = 115200
comObject.DataBits = 8
comObject.StopBits = 1
comObject.Handshake = IO.Ports.Handshake.None
comObject.Parity = IO.Ports.Parity.None
comObject.WriteTimeout = 1000
comObject.ReadTimeout = 1000
comObject.Encoding = System.Text.Encoding.GetEncoding(1252)
comObject.Open()
Dim ByteArray(sCommand.Length-1) as Byte 'sCommand contains the mentioned string
ByteArray = System.Text.Encoding.ASCII.GetBytes(sCommand)
comObject.DiscardInBuffer()
comObject.Write(ByteArray, 0, ByteArray.Length) 'in this case, the receiving device fails and i dont get any answere
ByteArray = {&H55, &H4A, &H42, &H33, &H41, &H30, &H31, &H30, &H31, &H39, &H32, &H32, &H31, &H30, &H34, &H33}
comObject.Write(ByteArray, 0, ByteArray.Length) 'this works fine and i receive 0x55 as answere, but i dont understand the difference
'between the manually generated ByteArray and ByteArray = System....GetBytes(sCommand)
Do
System.Threading.Thread.Sleep(10)
if comObject.BytesToRead >0 Then
sRetStr &= comObject.ReadByte.ToString("x2")
End If
Application.DoEvents()
Loop While(lStopWatch.ElapsedMilliseconds < lTimeout Or sRetStr.StartsWith(CStr(sCommand(0))))
send = True
Catch ex as Exception
sRetStr = ex.Message.toString()
send = False
End Try
End Function
I appreciate every kind of useful help.
By the way, I HAVE to use VB 2010 express,... I know, I know, but I have no other choice...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
