我正在从蓝牙HC05模块到Android手机接收3轴加速度计值。我有一个工作代码如下。 创建成功的连接和套接字后,这就是线程。
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
while (true) {
try {
bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
for(int i = begin; i < bytes; i++) {
if(buffer[i] == "#".getBytes()[0]) {
mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
begin = i + 1;
if(i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch
(IOException e) { }
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
现在,Handler类就是这样。
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int) msg.arg1;
int end = (int) msg.arg2;
switch (msg.what) {
case 1:
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
String data = writeMessage.toString();
String s[] = data.split(";");
txtX.setText(s[0]);
txtY.setText(s[1]);
txtZ.setText(s[2]);
break;
}
}
};
此处txtX,txtY,txtZ均为TextView。我的问题是,沿X和Z轴的加速度(即s [0]和s [1]值)可疑地波动。我的意思是Z轴振动通常在1400左右,但有时它会变成14000甚至1400000。并且对于s [0],实际传输的值约为508,但在很短的时间内,该值变为06或08。有人能找到从蓝牙读取的错误吗?