简体   繁体   English

Arduino / Android蓝牙延迟

[英]Arduino/Android Bluetooth delay

We are developping an app that uses Bluetooth library to communicate with an Arduino in bluetooth via an HC-05 module. 我们正在开发一个应用程序,该应用程序使用蓝牙库通过HC-05模块与蓝牙中的Arduino通信。 We made a dummy configuration to test the delay without any computation from eather the Arduino or the app and we have a huge delay of about 1 second between a request and an answer... 我们进行了一个虚拟配置来测试延迟,而无需从Arduino或应用程序进行任何计算,并且在请求和答案之间存在大约1秒的巨大延迟...

Protocol looks easy : Android send byte -2 and if byte received is -2, Arduino send -6, -9 and Android answer again and again. 协议看起来很简单:Android发送字节-2,如果接收到的字节为-2,则Arduino发送-6,-9,Android一次又一次地回答。

Android Code : Android代码:

h = new Handler() {
            public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                    case RECIEVE_MESSAGE:                                                   // if receive massage
                        byte[] readBuf = (byte[]) msg.obj;

                        for(int i=0;i < readBuf.length;i++)
                        {
                            if((int) readBuf[i] != 0) {
                                txtArduino.append(String.valueOf((int) readBuf[i]) + ", ");
                            }
                        }
                        byte[] msg = {-2};
                        mConnectedThread.writeByte(msg);
                        break;
                }
            };
        };

Arduino Code : Arduino代码:

const int receveidBuffLen = 8*4;


void setup() {
  Serial.begin(115200);
}

void loop() {
    if (Serial.available() > 0) 
    {
      byte buff[receveidBuffLen];
      Serial.readBytes(buff, receveidBuffLen);

      for(int i=0; i < receveidBuffLen;i++)
      {
        if(buff[i] == (byte) -2) // 254
        {
            byte message[2] = {(byte) -6, (byte) -9};
            Serial.write(message, 2);
            Serial.flush();
        }
      }
    }
    delay(3);
}

Does anyone know where the delay comes from? 有人知道延迟的来源吗?

We changed the HC05 baudrate (from 9600 to 115 200) : nothing happened. 我们将HC05波特率从9600更改为115200:什么也没发生。 We changed HC05 with another : nothing happened. 我们用另一个替换了HC05:什么也没发生。 We used the Blue2Serial library (Bluetooth as SPP) before and delay was the same... We used another controler (ESP8266) and delay still was 1 second... 之前我们使用Blue2Serial库(蓝牙为SPP),并且延迟相同...我们使用了另一个控制器(ESP8266),延迟仍然为1秒...

Looks like this string is an issue: 看起来这个字符串是一个问题:

Serial.readBytes(buff, receveidBuffLen);

Where receveidBuffLen is 32. Although you get single byte at a time, you're trying to read 32 of them. 其中receveidBuffLen为32。尽管您一次只能获得一个字节,但是您尝试读取其中的32个字节。 Of course, if there are no more bytes, the code will be stuck until timeout. 当然,如果没有更多字节,则代码将一直停留到超时。

Furthermore, after bytes is read, you never check how many bytes were actually read, but do scan whole the array from bottom to top: 此外,在读取字节之后,您无需检查实际读取了多少字节,而是从下至上扫描整个数组:

for(int i=0; i < receveidBuffLen;i++)

instead, you have to do something like this: 相反,您必须执行以下操作:

int bytesAvailable = Serial.available();
if (bytesAvailable > 0)
{
  byte buff[receveidBuffLen];
  int bytesToRead = (bytesAvailable < receveidBuffLen) ? bytesAvailable : receveidBuffLen;
  // Read no more than the buffer size, but not more than available

  int bytesActuallyRead = Serial.readBytes(buff, bytesToRead);

  for(int i=0; i < bytesActuallyRead;i++)
  ...

There are a couple problems with the code that might cause delays: 该代码有几个问题,可能会导致延迟:

  1. delay function at end of loop - This will slow down the processing that the Ardunio can keep up with 循环结束时的延迟功能-这会减慢Ardunio可以跟上的处理速度
  2. Calling Serial.flush() - This will block the processing loop() until the internal TX serial buffer is empty. 调用Serial.flush() -这将阻塞处理loop()直到内部TX串行缓冲区为空。 That means the Arduino is blocked and new RX data can pile up, slowing the response time. 这意味着Arduino被阻止,新的RX数据会堆积起来,从而降低了响应时间。
  3. Calling Serial.readBytes() - You should focus on the smallest unit of data and process that each loop() iteration. 调用Serial.readBytes() -您应该专注于最小的数据单元并处理每个loop()迭代。 If you are trying to deal with multiple message per loop, that will slow now the loop time causing a delay. 如果您试图在每个循环中处理多个消息,那么这将减慢循环时间,从而导致延迟。

You can try to implement a SerialEvent pattern on the Arduino. 您可以尝试在Arduino上实现SerialEvent模式。 We will only read one byte at a time from the serial buffer, keeping the processing that the loop() function has todo to a bare minimum. 我们一次只会从串行缓冲区读取一个字节,从而将loop()函数必须执行的处理保持在最低限度。 If we receive the -2 byte we will mark a flag. 如果我们收到-2字节,我们将标记一个标志。 If the flag is marked the loop() function will call the Serial.write() function but will not block for the data to transmit. 如果标记了该标志,则loop()函数将调用Serial.write()函数,但不会阻止数据传输。 Here is a quick example. 这是一个简单的例子。

bool sendMessage = false;
byte message[2] = {(byte) -6, (byte) -9};

void loop()
{
    if (sendMessage == true)
    {
        Serial.write(message, 2);
        sendMessage = false;
    }
}


/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent()
{
    while (Serial.available())
    {
        // get the new byte:
        byte inChar = ((byte) Serial.read());

        if (inChar == ((byte) -2))
        {
            sendMessage = true;
        }
    }
}

We just find some solutions by ourselves and want to share them : 我们只是自己找到一些解决方案,并希望与他们分享:

Initial situation : 1050 ms for an answer. 初始情况:1050毫秒为答案。 Alls solutions are independent and done with the initial situation. Alls解决方案是独立的,并已根据初始情况完成。

  • Remove Serial.flush() : 1022 ms. 删除Serial.flush():1022 ms。
  • Add a simple Serial.setTimeout(100) in Arduino Code : 135 ms. 在Arduino代码中添加一个简单的Serial.setTimeout(100):135毫秒。 (Oh man!) (天啊!)
  • Add a simple timeout to inputStream of 100ms in Android : 95 ms. 在Android中的100ms的inputStream中添加一个简单的超时 :95 ms。

Which solution is the best, we can't say but it works now... 我们不能说哪种解决方案是最好的,但现在可以使用...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM