Android Question Cannot write specific sequence of byte to serial port

fabton1963

Member
Licensed User
Hi ,
I'm writing a code that use serial port comunication.
I' need to write a specific sequence byte to serial port to initialize the attached device.

in hex
28 02 AF E7 FF 00 C1
decimal
40 2 175 231 255 0 193

In classic VB I may use the followin code:

With MSComm1
.Settings = "9600,n,8,1"
.InputMode = comInputModeBinary
End With
MSComm1.PortOpen = True
Dim Buffer As String

Buffer = Chr("&h28") & Chr("&h02") & Chr("&hAF") & Chr("&hE7") & Chr("&hFF") & Chr("&h00") & Chr("&hC1")
MSComm1.Output = Buffer



Using b4j or b4a I try using Astream object writing byte sequence
dim b() as byte
b(0) = 40
b(1) = 1
b(2) = 126
b(3) = 10
b(4) = 1
b(5) = 7
astream.Write( b)

works !!

b(0) = 40
b(1) = 1
b(2) = 234
b(3) = 228
b(4) = 1
b(5) = 7
astream.Write( b)

does not works !!!

I also try sendig word instead of byte with following code with no result !!

dim b(6) as string
Dim bc As ByteConverter
dim J as int

b(0) = "40"
b(1) = "2"
b(2) = "175"
b(3) = "231"
b(4) = "127"
b(5) = "0"
b(6) = "193"

For J = 0 To 6
Dim I As Short = data(J)
Dim bytes() As Byte = bc.ShortsToBytes(Array As Short(I))
Try
If astream.Write( bytes) Then
' ...
Else
' ...
End If
Catch
Log("error ...")
End Try
Next


Please help me.
 

Troberg

Well-Known Member
Licensed User
My guess: Byte numbers larger than 127 becomes negative numbers, and there, somewhere, things go bad. B4A uses signed bytes.

As for the last example, call me stupid, but I don't see how you go from b() to what you send. You fill b(), then you don't use it anymore.

I would probably just use more or less the VB variant and convert it to string, one character at the time, then send the string.
 

Erel

Administrator
Staff member
Licensed User
My guess: Byte numbers larger than 127 becomes negative numbers, and there, somewhere, things go bad.
It doesn't matter that that the bytes are signed. The correct value will be sent.

The problem is somewhere else.

You can write it like this:
B4X:
'Chr("&h28") & Chr("&h02") & Chr("&hAF") & Chr("&hE7") & Chr("&hFF") & Chr("&h00") & Chr("&hC1")
AStream.Write(Array As Byte(0x28, 0x02, 0xAF, 0xE7, 0xFF, 0x00, 0xC1))
 
Top