问题
Link successfully established and able to send data.
Android is sending SeekBar data when ever we change it.
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(seekBar.getId() == R.id.seekBar)
{
speed.setText(String.valueOf(progress));
String outputData = String.valueOf(progress);
streams.write(outputData.getBytes());
}
}
streams.write()
writes data to the OutputStream
of the Socket
.
Problem is with the format of data.If I Send '25' arduino is receiving '2','5' when I do Serial.read()
.
What is the format of data, when outputData
is converted into bytes? Is everything terminated by \0
?
I need to retrieve the whole number instead of single digits.
回答1:
the arduinoboard seems to read the RX-Stream byte by byte. If you send "25" it transmits the ascii byte for the character'2' (which is 0x32 / decimal 50) and then the ascii representation for the character '5' (which is 0x35 / decimal 53). The arduino interprets these numbers as characters. So if the number you want to transmit is lower than 256 you can do: On Android:
if(seekBar.getId() == R.id.seekBar)
{
speed.setText(String.valueOf(progress));
if(progress<256)
streams.write((byte)progress);
}
To make sure the Arduino interprets it right, use the received character as a short and not as a character.
Hope this helps
回答2:
For the sender side, the getBytes() does not return a C string with a null terminator. In Java, arrays contain information about their length. So the byte[] contains its length; it is not like a C char[] which uses a null to indicate the end of the array. If you want to translate the outbound data you need to add the terminator yourself:
String outputData = String.valueOf(progress);
streams.write(outputData.getBytes());
streams.write('\0');
Note that the getBytes() can completely break down if the the character set default encoding changes on the Android side. On a different Android device, the getBytes() could return unicode character set encoding, which the Arduino would not be able to decode.
回答3:
You have an int, convert it to a string and send the string:
String outputData = String.valueOf(progress);
streams.write(outputData.getBytes());
How about just sending the int:
streams.write( progress );
On the Arduino side Serial.read() reads a byte at a time, so (assuming big endianess on the wire) you could do
int incomingByte = Serial.read();
incomingByte <<= 8;
incomingByte |= Serial.read();
Cheers,
来源:https://stackoverflow.com/questions/14893860/android-arduino-bluetooth-communication