【发布时间】:2014-07-22 10:53:16
【问题描述】:
我有 Android Arduino 蓝牙通信。有时 Android 会收到两条消息,而不是来自 Arduino 的一条消息。我的意思是:如果我寄给前任。通过蓝牙从 Arduino 到 Android 的 5 字节消息“1234”,有时我在一条消息中得到“1”1 字节,在第二条消息中得到“234”+\n 4 字节。有时我会收到完整的“1234”+\n 5 字节消息,但不知道为什么。我需要通过分隔符拆分输入消息,如果我收到单独的消息,我会崩溃。所以我需要将字节附加到字符串,直到新行字符出现。
- 如何将字符添加到字符串中,直到出现“\n”新行字符?
数据来的情况:
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 将字符添加到字符串中,直到出现新行字符。
【问题讨论】: