Arduino Bluetooth - send but not receive

headingwest

Member
Licensed User
Hi All,

I have an Arduino with the HC-05 bluetooth.

Adapting the example code for the bluetooth library I can send text to the Arduino, but I get rubbish back. In fact the return text has different number of bytes depending on the character.

The core Arduino code returns the same byte it receives:
B4X:
while (Serial1.available() > 0) {
      inByte = Serial1.read();    // Get the received Byte works fine
      Serial.write(inByte);       // Write Byte to serial monitor
      bFoundData = true;
      Serial1.write(inByte);      // Return Byte value to bluetooth as reply
    }
And I would think that the B4A would accept it back:

B4X:
Sub AStream_NewData (Buffer() As Byte)
   
   sByteIn = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
   sb.Append(sByteIn)
   
   If sByteIn.EndsWith(CRLF) Then
      LogMessage("You:", sb.ToString)
      sb.Remove(0, sb.Length)
   End If
   
End Sub
So if I send "h" I want "h" back. But the return byte is -5

Here are some sample send and return values

h -5
i 86
j -106 and then -5 (2 bytes are returned)
k -5
l 22 and then -5 (2 bytes are returned)

Any ideas??
 

agraham

Expert
Licensed User
Bytes are regarded as signed in Java so get sign extended when cast to a wider type like Int. If you want a positive value you can mask the result with Bit.And. Try
B4X:
 SomeVar = Bit.ParseInt(Bit.And(SomeByte, 0xff), 16)
You might need to mask the parity bit as well.

Also sb.Append(sByteIn) appends the value of the byte not the character it represents. Try sb.Append(Chr(sByteIn))
 

headingwest

Member
Licensed User
Thanks AGraham, partially solved. There's something else happening in the AsyncStreams, here is a test event:

B4X:
Sub AStream_NewData (Buffer() As Byte)
   Dim holdVar As Byte 
   Dim lenbyte As Int
   lenbyte = Buffer.Length 
   holdVar = Buffer(0)   
End Sub
This event only fires on certain byte values returned:
a - 97
b - 98
c - event fails to fire
d - 100
e - event fails to fire
f - event fails to fire
g - 103
h - 104

etc. This is replicable so "c" never triggers the NewData event while "a" always triggers the event.
 

headingwest

Member
Licensed User
I just tried the most basic send from the Arduino:
B4X:
Serial1.write(103);
103 triggers the NewData event in b4A
102 does not trigger the NewData event in B4A
 
Top