我想从我的arduino mega ADK板发送数据到我的Android应用程序并显示此信息。我在处理程序方面遇到了很多麻烦,但我确实有效。然而,我的问题不是显示信息,而是显示信息的循环。每当我运行我的arduino板时,它会继续运行大约30秒,并继续向应用程序发送数据,因为我可以在串行监视器中看到这一点。然后,应用程序只显示一次接收的数据,串行监视器显示循环已停止。我想继续在我的Android应用程序中看到收到的信息。 另请注意,我按下按钮后,让我的Android应用程序向我显示收到的数据。但是它只显示一次,我不能再次按下按钮再次检查显示。 (再次说明我不想再按下按钮。按下按钮一次后,它应该连续显示接收到的数据。)
另外,实际调用run方法应该在哪里?
Android代码:
public void run()
{
int ret = 0;
byte[] buffer = new byte[100];
int i;
while (true) // read data
{
try
{
ret = mInputStream.read(buffer);
}
catch (IOException e)
{
break;
}
i = 0;
while (i < ret)
{
int len = ret - i;
if (len >= 1)
{
Message m = Message.obtain(mHandler);
int value = (int)buffer[i];
// 'f' is the flag, use for your own logic
// value is the value from the arduino
m.obj = new ValueMsg('f', value);
mHandler.sendMessage(m);
}
i += 1; // number of bytes sent from arduino
}
}
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg)
{
ValueMsg t = (ValueMsg) msg.obj;
mResponseField.setText("Flag: "+t.getFlag()+"; Reading: "+t.getReading()+"; Date: "+(new Date().toString()));
}
};
这是调用run()
方法的地方:
testButton = (Button) findViewById(R.id.button3);
testButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
run();
}
});
这是Arduino代码:
#include <CapacitiveSensorDue.h>
#include <Wire.h>
#include <Servo.h>
#include <Max3421e.h>
#include <Usb.h>
#include <AndroidAccessory.h>
#include <CapacitiveSensor.h>
AndroidAccessory acc("Google, Inc.",
"DemoKit",
"DemoKit Arduino Board",
"1.0",
"http://www.android.com",
"0000000012345678");
void setup()
{
Serial.begin(115200);
Serial.print("\r\nStart");
Serial.print("\r\nStartSetup");
acc.powerOn();
}
void loop()
{
Serial.println("\r\nLOOPStart");
byte msg[1]; // one byte
char value=10;
if (acc.isConnected()) {
while(value>0)
{
Serial.print("\r\nawe");// count down
msg[0] = value;
acc.write(msg, 1);
Serial.print(value);
value-=1;
delay (1);
}
while(value<=10)
{
// count up
msg[0] = value;
acc.write(msg, 1);
value+=1;
delay (1);
}
delay (1);
}
}