我正在使用Android 4.4.4的2013 Nexus 7和带有HC-06蓝牙装置的Arduino Mega 2560进行通信。我建立了从Nexus 7到HC-06的连接,并从Arduino获得了Nexus的gotton数据,但我无法将数据从Nexus 7传输到Arduino。我在Android中传输数据时没有出错,但Arduino收到的是空格而不是我发送的字符。
Android写法:
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.e(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
发送数据:
public static void sendInfo(String info) {
boolean isErr = false;
if (MainActivity.isConnected) {
Log.d(TAG, "In sentInfo()");
//Log.d(TAG, "...Data to send: " + info + "...");
//TO(done)DO: send info to bluetooth device (Arduino)
try {
mConnectedThread.write(info);
} catch (NullPointerException n) {
isErr = true;
Log.e("Error", "Failed to send message \"" + Arrays.toString(msg) + "\" with error \"" + n.getMessage() + ".\"");
}
if (!isErr) {
Log.i("sentInfo", "In sentInfo(), this was sent: " + Arrays.toString(msg));
//noinspection ALL
isErr = false;
}
} else {
Toast.makeText(MainActivity.mThis, "Please connect the Arduino", Toast.LENGTH_SHORT).show();
}
}
Arduino收到代码:
int setMsg() {
if (Serial1.available() > 0) {
chars = Serial1.available();
incomingByte = Serial1.read();
putstring("You've Got Mail! Characters: ");
Serial.print(chars);
putstring(" Message: '");
Serial.print(incomingByte);
putstring_nl("'.");
if (incomingByte == 49) {
return 1;
flashLED(500);
Serial.println(msg);
} else if (incomingByte == 50) {
return 2;
flashLED(500);
Serial.println(msg);
} else if (incomingByte == 51) {
return 3;
flashLED(500);
Serial.println(msg);
} else if (incomingByte == 52) {
return 4;
flashLED(500);
Serial.println(msg);
} else if (incomingByte == 53) {
return 5;
flashLED(500);
Serial.println(msg);
} else if (incomingByte == 100) {
return 6;
flashLED(500);
Serial.println(msg);
} else {
Serial.println(incomingByte);
digitalWrite(ledPin, HIGH);
delay(3250);
digitalWrite(ledPin, LOW);
delay(20);
return 0;
}
}
}
请解释为什么Arduino Serial
始终打印
You've Got Mail! Characters: 1 Message: ' '.
当Nexus 7向HC-06发送任何消息(我只将引号中的数字发送到sendInfo()
功能)时。{/ p>
答案 0 :(得分:0)
根据您的评论进行修改:
incomingByte needs to be an int
将您的阅读代码更改为:
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
}
void loop() {
// read from port 0, send to port 1:
if (Serial.available()) {
int inByte = Serial.read();
Serial1.print(inByte, BYTE);
}
// read from port 1, send to port 0:
if (Serial1.available()) {
int inByte = Serial1.read();
Serial.print(inByte, BYTE);
}
}
(我只将引号中的数字发送到sendInfo()函数)到HC-06。
你不应该在引号中发送数字,只是一个数字。这可能是你的问题,因为它正在读取引号。
此外,使用开关代替所有ifs可能更好
此byte[] msg = info.getBytes();
中的sendInfo(String info) {
是不必要的行,您从我看到的内容中未使用它,您将字符串解析为{{1}中的字节数组}}
而不是write(string) method
你可以Log.i("sentInfo", "In sentInfo(), this was sent: " + Arrays.toString(msg));
以及你在返回之后拥有的所有东西,如果,将不会被执行
Log.i("sentInfo", "In sentInfo(), this was sent: " + info);
要在每个if语句中执行的任何内容都需要在return语句之前放入,返回将导致函数完成并返回到调用函数。