我的Arduino正在侦听从我的手机发送的字符以打印传感器数据以通过蓝牙模块发回。这工作正常,通信快速准确。但是,当我从两个不同的传感器请求数据时,就会出现问题。
我将从传感器 A 请求数据并得到我的结果。然后我从传感器 B 请求数据,我得到了似乎是对传感器 A 的剩余请求,并再次从传感器 A 获取信息。我可以连续两次向传感器B请求数据,然后我将准确地从传感器B接收数据。
我试图刷新输入流,但这使我的应用程序崩溃。我还尝试使用 InputStream.wait(),然后在从其他传感器请求数据时使用 InputStream.notify() 中断等待。这也使程序崩溃。
这是我的接收代码。传入的字符是定义要从 Arduino 发回的传感器数据的字符。
public String receive(Character c) {
try {
myOutputStream.write(c);
final Handler handler = new Handler();
final byte delimiter = 10; // ASCII code for a newline
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
myThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()
&& !stopWorker) {
try {
int bytesAvailable = myInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
myInputStream.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() {
status = data;
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex) {
stopWorker = true;
}
}
}
});
myThread.start();
return (status);
}
catch (IOException e) {
// TODO Auto-generated catch block
status = "Failed";
e.printStackTrace();
}
return (status);
}
这是一些Arduino代码,非常简单。
if(bluetooth.available()) //If something was sent from phone
{
char toSend = (char)bluetooth.read(); //Reads the char sent
if (toSend == 'T')
{
//If the char is T, turn on the light.
float voltage = analogRead(14) * 5.04;
voltage /= 1024.0;
float temperatureC = (voltage - .5) * 100;
float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
bluetooth.println(temperatureF);
}
我该如何解决这个问题?