I am constantly sending two short numbers (18 90) using BluetoothSPP library from Android to Arduino using this code
byte[] array = new byte[4];
for (int i = 0; i < 2; i++) {
array[i] = shortToBytes((short)18)[i];
}
for (int i = 2; i < 4; i++) {
array[i] = shortToBytes((short)90)[i-2];
}
if (bt.isServiceAvailable()){
bt.send(array);
}
I am using shortTo|Byte method to create byte array from short:
public byte[] shortToBytes(final short i) {
ByteBuffer bb = ByteBuffer.allocate(2);
bb.putShort(i);
return bb.array();
}
This code is receiving short from Android and sending them to my PC:
byte array[4];
int left;
int right;
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
}
void loop() {
if (Serial1.available() >= 4)
{
for (int i=0; i <=4 ; i++)
{
array[i] = Serial1.read();
}
left = array[1] | ( array[0] << 8 ) ;
right = array[3] | ( array[2] << 8 ) ;
Serial.print("0 ");
Serial.println(left);
Serial.print("1 ");
Serial.println(right);
}
}
Problem is sometimes I am receiving right values and sometimes I don't:
Because I am wanting to send numbers between -32000 : +32000 range, so I need short for this. Function *shortToBytes * does convert one short number to array of two bytes.
2573 decimal == 0xA0D, which is newline followed by carriage return
Your code as you have it needs to read 6 bytes and use the last 2 as end of line markers -- gives you an error check.
Edit again: actually since your code reverses byte order ( array[0] is high byte, array[1] is low ) you are getting 0D 0A, not 0A 0D. Carriage Return then Newline is the more standard order.