First off, you are only sending one byte from Android:
public abstract void write (int b)
Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.
OutputStream.write(byte) can never write more than one byte.
Also it's clear you have no clue about what format the data is sent in if you are trying to then read 3 bytes and use Binary Coded Decimal to reconstruct it.
Instead I suggest you work in a purely ASCII format. Forget bytes. Bytes are not what you want, unless you feel like spending some extra time defining, and then implementing, your own protocol.
Start by formatting your data into an ASCII printable string. If Android Java is anything like normal Java I'd start by turning your integer into a string with proper line endings. Something like:
String val = String.format("%d\n", angle);
Then get the bytes that represent that formatted string:
byte[] valBytes = val.getBytes();
Now you have a valid byte array containing your textual representation of the data that you can send with OutputStream.write(byte[])
.
Now your task is to read that data on the Arduino. That means reading each byte that arrives in turn storing it away in some form until you receive the \n
line ending. At that point you can take each byte as a string and convert them into an integer again.
It's possible to do that on the fly:
static int angle = 0;
if (Serial.available()) {
char c = Serial.read();
if (c == '\n') {
Serial.print("I got: ");
Serial.println(angle);
angle = 0;
} else if ((c >= '0') && (c <= '9')) {
angle *= 10;
angle += (c - '0');
}
}
Basically, have a variable that stores the incoming angle. For each character that arrives on the serial port - if it's a line ending \n
then do whatever with the angle value. If it's a character between 0 and 9 then multiply your angle by 10 (decimal shift left), convert your character to the equivalent integer by subtracting character '0', and add it to your angle.