我有Android< - > Arduino蓝牙通信。有时Android会从Arduino获取两条消息,而不是一条消息。我的意思是:如果我发送给前任。 5字节消息" 1234"从Arduino到Android通过蓝牙,有时我会得到" 1"一条消息中有1个字节,第二条消息中有" 234" + \ n 4个字节。有时我会得到满满的" 1234" + \ n 5字节消息,并且没有任何线索的原因。我需要通过分隔符拆分输入消息,如果我收到单独的消息,我会崩溃。所以我需要将字节追加到字符串直到新行char来。
数据出现的情况:
case BLUETOOTH_RECEIVED:
byte[] buffer = (byte[])msg.obj;
int len = msg.arg1;
if (len > 0 && buffer != null) {
onBluetoothRead(buffer, len);
}
break;
}
缓冲区到字符串:
private void onBluetoothRead(byte[] buffer, int len) {
Log.i(LOGGER_TAG, String.format("Received: " + output.replace("\n", "") + " message of " + "%d bytes", len));
String output = new String(buffer, 0, len); // Add read buffer to new string
m_deviceOutput.append(output); // Add (not replace) string to TextView
StringTokenizer splitStr = new StringTokenizer(output, ","); // split string by comma
String numberOne = splitStr.nextToken(); // First split string
String numberTwo = splitStr.nextToken(); // Second split string
numberOne = numberOne.replaceAll("\\D+",""); // replace all chars, leave only numbers
numberTwo = numberTwo.replaceAll("\\D+","");
}
logcat的:
07-22 14:06:15.099: I/DeviceActivity(20370): Received: 1234 message of 5 bytes
07-22 14:06:20.599: I/DeviceActivity(20370): Received: 1234 message of 5 bytes
07-22 14:06:27.349: I/DeviceActivity(20370): Received: 1 message of 1 bytes
07-22 14:06:27.469: I/DeviceActivity(20370): Received: 234 message of 4 bytes
07-22 14:06:37.219: I/DeviceActivity(20370): Received: 1 message of 1 bytes
07-22 14:06:37.349: I/DeviceActivity(20370): Received: 234 message of 4 bytes
在Arduino我可以这样写,我想要类似的东西:
//Get data from RS485:
void READ01(){
while (mySerial.available()){
mySerial.read();
}
mySerial.println("01READ");
momentas1="";
delay(20);
while (mySerial.available()) {
char c = mySerial.read();
if (c == '\n'){
break;
}
momentas1 += c;
}
}
此void READ01
将字符串添加到字符串,直到新行字符来。
答案 0 :(得分:2)
您可以使用类似缓冲区的实现,方法是将获取的字符串添加到另一个字符串,直到收到“\ n”。
private String packet = "";
private void onBluetoothRead(byte[] buffer, int len) {
Log.i(LOGGER_TAG, String.format("Received: " + output.replace("\n", "") + " message of " + "%d bytes", len));
String output = new String(buffer, 0, len); // Add read buffer to new string
packet += output;
if (packet.endsWith( "\n" ) {
//do what you need to do
m_deviceOutput.append(output); // Add (not replace) string to TextView
StringTokenizer splitStr = new StringTokenizer(packet, ","); // split string by comma
String numberOne = splitStr.nextToken(); // First split string
String numberTwo = splitStr.nextToken(); // Second split string
numberOne = numberOne.replaceAll("\\D+",""); // replace all chars, leave only numbers
numberTwo = numberTwo.replaceAll("\\D+","");
packet = "";
}
}