我使用教程Data transfer between Android and Arduino via Bluetooth从 Arduino 接收代码。
我用 id txtArduino 制作了一个文本视图,我使用了.append
,但是为什么当 Arduino 发送时我收到不完整的文本?
例如:
LED 亮起,并且:w- 。输入:13
还有类似这样的奇怪文字。
我该如何解决这个问题?
PS:如果需要,我可以提供更多代码。
安卓标头
h = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // If receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // Create string from bytes array
sb.append(strIncom); // Append string
int endOfLineIndex = sb.indexOf("\r\n"); // Determine the end-of-line
if (endOfLineIndex > 0) { // If end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // Extract string
sb.delete(0, sb.length()); // And clear
txtArduino.append(sbprint + "\n"); // Update TextView
//toggleDOOR.setEnabled(true);
}
Log.d(TAG, "...Mesaj:"+ sb.toString() + " Byte:" + msg.arg1 + "...");
break;
}
};
};
Arduino代码:
int cnt = 0;
int pinLed = 13;
String myKey = "0000001";
//Pin Geam Masina 2 si 3
int pinGeamInchis = 2;
int pinGeamDeschis = 3;
char incomingByte;
void setup(){
Serial.begin(9600);
//INITIALIZARE
pinMode(pinLed,OUTPUT);
pinMode(pinGeamInchis,OUTPUT);
pinMode(pinGeamDeschis,OUTPUT);
digitalWrite(pinLed,LOW);
Serial.print("Modul ON( KEY:");
Serial.print(myKey);
Serial.print(" )\r\n");
}
void loop(){
if(Serial.available()> 0){
incomingByte = Serial.read();
if(incomingByte == '0'){
//Opreste LED
digitalWrite(pinLed,LOW);
Serial.print("Pin 13: LED OFF\r\n");
//Inchide Geam
digitalWrite(pinGeamInchis,HIGH);
Serial.print("Command:W-C\r\n");
delay(500);
digitalWrite(pinGeamInchis,LOW);
Serial.print("Pin 2:Window Down\r\n");
}
if(incomingByte == '1'){
//Aprinde LED
digitalWrite(pinLed,HIGH);
Serial.print("LED ON\r\n");
//Deschide Geam
digitalWrite(pinGeamDeschis,HIGH);
Serial.print("Command:W-O\r\n");
delay(500);
digitalWrite(pinGeamDeschis,LOW);
Serial.print("Pin 3:Window Up\r\n");
}
}
}
我明白了,如果我只发送一个“命令”,它就可以工作。我该怎么做才能在串行和 Android 上接收更多命令?
PS:我使用Arduino Nano。