【发布时间】:2016-01-17 09:57:27
【问题描述】:
我编写了 Android 代码来连接蓝牙 HC-05,向 HC-05 发送命令并接收与发送的命令相关的不同数据。 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();
}
}
请帮忙!!
【问题讨论】: