【发布时间】:2013-11-03 21:24:04
【问题描述】:
在这个问题之后 Bluetooth connection in Android > 4.1.2 我通过反复尝试连接一段时间迭代来强制连接来修复,现在我遇到了 Android/Arduino 通信的另一个问题。 我的硬件是 Nexus 7 MY2012,搭载 Android 4.3、Arduino UNO R3 和 BT 模块 RN42。
我从 Android 向 Arduino 发送从字符串获取的字节数组。 一开始,波特率为 115200 且没有奇偶校验,只有第一个字节正确到达,其余字节显然不匹配(主要以重复的方式)。 在 RN42 模块中设置奇偶校验 EVEN 后,我看到至少前 3 个字节正确到达,其余的都搞砸了。 下面是Android通信的核心部分(BT的初始化基本遵循SDK示例)。它位于用于管理连接工作的 AsyncTask 的类中:
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
mHardwareToServiceHdlr.obtainMessage(MSG_ERR_BT_WRITE).sendToTarget();
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
和 Arduino 草图
#include <SoftwareSerial.h>
#include <Streaming.h>
const int bluetoothTx = 2;
const int bluetoothRx = 3;
byte incomingByte;
String incomingString;
SoftwareSerial bluetooth(bluetoothTx,bluetoothRx);
void setup() {
Serial.begin(115200);
bluetooth.begin(115200);
bluetooth.print("$$$");
delay(100);
bluetooth.println("U,115K,E");
bluetooth.begin(115200);
delay(100);
}
void loop(){
if (bluetooth.available() > 0) { // if the data came
incomingByte = bluetooth.read(); // read byte
Serial.println((char)incomingByte);
}
}
如果我向 Arduino 发送一个字符串,例如“hello horld”,这就是我在串行监视器中的一系列传输:
hel,o wo2ld
hel<o wo2ld
hel,o7orld
hel,o wo2ld
hel,o wo2ld
hel<o7or6d
hel,o wo2ld
hel,o wo2ld
hel,o wo2ld
hel<o wo2ld
hel,o7orld
hel<o wo2ld
这只是示例,结果还取决于我将字符串发送到 Arduino 的频率。 大多数情况下,第四个和第九个字节(但并不总是以相同的方式,也不总是只有它们)不匹配。
从 Arduino 向 Android 传输数据似乎可以解决任何特殊问题。
任何帮助将不胜感激,这件事让我发疯,因为我需要传输超过 3 个字节的数据。 谢谢
【问题讨论】:
-
嗨!我无法接收从 Android 发送的数据,但我能够接收来自 Arduino 的数据。你遇到过这样的问题吗?
标签: java android bluetooth arduino