我的Arduino正在侦听从手机发送的字符,以打印传感器数据以通过Bluetooth模块发回。这工作正常,沟通快速准确。但是,当我从两个不同的传感器请求数据时会出现问题。
我将从传感器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);
}
如何解决此问题?