B4J Question USB Serial Port

ElliotHC

Active Member
Licensed User
Hi

I've just come to do a project where I need to read bytes coming in from the serial port, is there a simple example I can dissect?

Thanks
 

ElliotHC

Active Member
Licensed User
If you're just sending text lines, then it's not hard to accumulate the incoming characters into a buffer and then dole them out when you have a complete line, eg:
B4X:
Dim TextBuffer As String    'global serial port input buffer

Sub AStream_NewData (Buffer() As Byte)
 
    'add to buffer
    TextBuffer = TextBuffer & BytesToString(Buffer, 0, Buffer.Length, "UTF8")

    Dim EOLChar As String = Char(13)    'or 10 or 0 or whatever

    'dole out lines (if any)
    Do While True
        Dim EOLCharAt As Int = TextBuffer.IndexOf(EOLChar)
        If EOLCharAt = -1 Then
            Exit
        End If

        Dim TextLine As String = TextBuffer.SubString2(0, EOLCharAt)    'get next line
        TextBuffer = TextBuffer.SubString(EOLCharAt + 1)    'remove from buffer

        HandleTextLine(TextLine)
    Loop

End Sub
or if you prefer clarity over efficiency, you could change this bit:
B4X:
'''Do While True
'''    Dim EOLCharAt As Int = TextBuffer.IndexOf(EOLChar)
'''    If EOLCharAt = -1 Then
'''        Exit
'''    End If

Do While TextBuffer.Contains(EOLChar)
    Dim EOLCharAt As Int = TextBuffer.IndexOf(EOLChar)    'should always find EOLChar


I'll try that first, thanks.
 
Upvote 0

emexes

Expert
Licensed User
Check AsyncStreamsText.
Spewin! I was wondering if the file text line functions might work, but figured they'd need a timer to convert from polled to event-driven, and apparently this app is needed tomorrow, so I didn't pursue that angle.

Now me with my crystal ball is looking a bit of a dunce again, but... all's well that ends well :)
 
Last edited:
Upvote 0
Top