0
我已经编写了Android代码连接到蓝牙HC-05,向HC-05发送命令并接收与发送的命令相关的不同数据。 Android应用程序连接蓝牙和发送第一条命令时,它会收到我想要的确切数据,但下一条命令会收到符号“ ”以及相关数据。Android蓝牙串行通信读取符号“ ”
我已经测试了与其他蓝牙终端在Android上的硬件电路,它的工作原理是完美的。
以下是我的串行通信代码:
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes,"US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
sampleView.setText(data);
str = sampleView.getText()
.toString();
Log.i("Data", data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
try {
String command1=command.getText().toString();
mmOutputStream.write(command1.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
请帮助!
对不起延迟回复...我曾尝试“UTF-8”,但情况没有改变。 – user2718012
这个符号的HEX表示是什么?它不一定是“ ”,但可能是“无法识别”字符的表示。 我想问题是你的分隔符检测。如果HC-05发送的UTF字符的低位字节为0x10,则可能会被您的代码误解。 – Andrew
如果问题是分隔符检测,那么它总是会发送这个符号。但在第一个命令的情况下,它发送正确的数据和第二个命令,它的代码读取符号和数据。你认为我应该在上面的代码中做出什么改变? – user2718012