Arduino and USB

NewB4a

Member
Licensed User
Longtime User
My Arduino Board sends for testing purpose incremented numbers by:
HTML:
Serial.println(Counter,DEC);
With the serial Monitor I can control the correct sending.
With a connect Button I open the connection:
HTML:
Sub BtnConnect_Click
   If USB.UsbPresent = USB.USB_NONE Then
      Msgbox("No USB device or accessory detected!", "Error")
      Return
   Else
      If (USB.HasPermission) Then
         Dim dev As Int
         dev = USB.Open(9600)   
         If dev <> USB.USB_NONE Then
            Log("Connected successfully!")
            AStream.Initialize(USB.GetInputStream, USB.GetOutputStream, "AStream")
         Else
            Log("Error opening USB port")
         End If
      Else
         USB.RequestPermission
      End If
     End If
End Sub
My b4a-solution receives data:
HTML:
Sub AStream_NewData (Buffer() As Byte)
   temp=""
   For i = 0 To Buffer.Length -1
     If Buffer(i)=13 Then  'Zeilenende wg serial.println
       Msgbox(temp,"von Arduino")
       temp=""
     Else
       temp=temp&BytesToString(Buffer,i,Buffer.Length,"UTF8")
     End If
   Next
End Sub
But in most of the cases I get an 'error in main_astream_newdata' 'StringIndexOutofBoundsException'. I suppose, that this concern the index of Buffer(). Is the termination If Buffer(i)=13 correct or how to change it?
 

agraham

Expert
Licensed User
Longtime User
This line is wrong.
B4X:
 temp=temp&BytesToString(Buffer,i,Buffer.Length,"UTF8")
The third parameter is the number of bytes to read but even with that, as you are calling it in a loop the result in temp will have repeated occurrences of characters already read. I'm not sure that is what you want.

That is a clumsy way of converting to text anyway and doesn't take into account that your messages are likely to be received piecemeal and not in one data block. Try using AsyncStreamsText which will also deal with the fact that your messages are likely to be received in fragments.
 
Last edited:
Upvote 0
Top