B4J Question Serial receving wrong replies

aaronk

Well-Known Member
Licensed User
Longtime User
Hi,

I am trying to send serial data to a device connected by a USB-to-RS232 cable.

I looked at the Library: https://www.b4x.com/android/forum/threads/jserial-library.34762/#content

Using jSerial version 1.20

I have used the following code:

B4X:
Sub Process_Globals       
    Private sp As Serial
    
    Private astream As AsyncStreams
    Private connected As Boolean
    
End Sub

Sub AppStart (Args() As String)
        
    sp.Initialize("")
    
    Log(sp.ListPorts)
    connected = False
    
    Connect(sp.ListPorts.Get(1))
    
    StartMessageLoop
End Sub
Sub AStream_NewData (Buffer() As Byte)
    Dim s As String
    s = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    
    Dim msg() As String
    msg = Regex.Split(CRLF,s)
    
    For x = 0 To msg.Length - 1
        Log("Rx: " & msg(x))   
    Next
End Sub

Sub AStream_Error
    Log("Error: " & LastException)
    astream.Close
    AStream_Terminated
    connected = False
End Sub

Sub AStream_Terminated
    Log("Connection is broken.")
    connected = False
End Sub

Sub Connect(ComPort As String)
    Log("Connecting to Port: " & ComPort)
    
    sp.Open(ComPort)
    sp.SetParams(9600,8,1,0)
    astream.Initialize(sp.GetInputStream, sp.GetOutputStream, "astream")
    
    connected = True

    SendData("ABC123")

End Sub

Public Sub SendData(msg As String)
    Log("connected = " & connected)
    Log("Send: " & msg)
    If connected Then astream.Write(msg.GetBytes("UTF8"))
End Sub

The receiving side receives the command fine.

The receiving side then sends the reply, except in my B4J app it receives random data and not the reply I am wanting.

I then used another RS232 software tool for testing, and sent the same command and I am getting the reply I am meant to get.

Seems that my B4J app isn't receiving the reply correctly.

Meant to connect as:
9600
8 data bits
no parity
1 stop bit

B4J receives:
B4X:
Connecting to Port: COM3
connected = true
Send: ABC123
Rx: 870003
Rx: 612401011901291
Rx: 721264e
Rx: 8700036122000
Rx: 119012917212651

The other RS232 software receives: (which is what it should of returned)
B4X:
Tx: ABC123
Rx: 8700036124010119012917230270
Rx: 8700036122000119012917230273

Using the same RS232 port, and USB cable.

Any ideas on what I have done wrong ?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
You shouldn't assume that messages will not be merged or split. If each message ends with an end of line character then use AsyncStreamsText to parse the messages. Otherwise you need to take care of it yourself based on the specific protocol. BytesBuilder will be very helpful for this.

https://www.b4x.com/android/forum/threads/101071/#content
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…