我通过USB将我的Android设备连接到arduino,我通过使用bulkTransfer立即从arduino接收数据,但是当我要使用相同的命令将确认信号发送回arduino时,它会在几秒钟之后收到。
我的arduino模型是DUE,arduino端代码是:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(49, OUTPUT);
}
void loop() {
String a;
int sensorValue[64];
for (int i = 0; i <= 63; i++)
{
sensorValue[i] = analogRead(A0) / 4;
a = a + char(sensorValue[i]);
}
char b;
while (1) {
Serial.print(a);
Serial.flush();
delay(2);
b = Serial.read();
if (b == '1')
{
break;
}
}
digitalWrite(49, HIGH);
delay(2000);
digitalWrite(49, LOW);
}
我的android端代码是:
public void onClick(View v) {
synchronized (this) {
if (usbDeviceConnection != null) {
Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
try {
int chunkCounter = 0;
String strTemp = null;
while (chunkCounter < 1) {
byte[] message = new byte[64];
final int result = usbDeviceConnection.bulkTransfer(endpointIN, message, 64, 10);
if (result == 64) {
for (int intTemp = 0; intTemp < 64; intTemp++) {
strTemp += String.valueOf((char) message[intTemp]);
}
byte[] ack = new byte[1];
ack[0] = 1; //1 means I've got this chunk
synchronized(this) {
int resultAck = 0;
while (resultAck <= 0) {
resultAck = usbDeviceConnection.bulkTransfer(endpointOUT, ack, 1, 10);
}
}
chunkCounter++;
if (chunkCounter == 1) {
final String strTempFinal = strTemp;
tempflag = true;
runOnUiThread(new Runnable() {
@Override
public void run() {
txtGetData.setText(strTempFinal);
}
});
}
}
}
} catch (final Exception e){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
myThread.start();
}
任何帮助将不胜感激。 提前谢谢。