gpt4 book ai didi

java - Android 通过 RN42 蓝牙模块与 Arduino 的通信不匹配

转载 作者:行者123 更新时间:2023-12-01 04:12:45 26 4
gpt4 key购买 nike

出现此问题后 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 个字节的数据。谢谢

最佳答案

您的设置可能存在多个问题:

  1. 不要多次使用SoftwareSerial的begin()。如果您需要清空缓冲区,请在 println() 之后和延迟之前使用 bluetooth.flush()
  2. 取自SoftwareSerialdocs :

    If using multiple software serial ports, only one can receive data at a time.

    尝试使用 UART 作为串行端口,而不是位连接串行端口。

  3. Arduino UNO 仅支持引脚 2 和 3 的中断,它们经常用于其他用途,请检查它们在您的设计中是否确实是空闲的。

  4. 尝试使用较低的波特率,115200 bps 的布局甚至可能会出现 RF 问题。

  5. 如果前面的方法不起作用,请尝试在主循环中执行 Serial.print 之前将字符存储在缓冲区中。完成后,最后打印它,如下所示(注意边界检查):

    char buffer[MAX_LEN];
    unsigned int count = 0;

    void loop(){

    if (bluetooth.available() > 0) { // if the data came
    buffer[count++] = bluetooth.read(); // read byte
    }
    buffer[count] = '\0';
    Serial.print(buffer);
    count = 0;
    }

关于java - Android 通过 RN42 蓝牙模块与 Arduino 的通信不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19758314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com