使用 HC-05 将连续数据从 arduino 发送到 Android App

Sending continuous data from arduino to Android App using HC-05

我一直在努力解决从arduino向Android发送连续数据的问题。 我想要做的是获取模拟读取并将其转换为 0-5V 信息,并将该信息发送到 Android 应用程序。 我的arduino代码很简单:

//(...)defining pins and levels
SoftwareSerial BTSerial(rxPin, txPin);
void setup()
{
  pinMode(getData, INPUT);
  digitalWrite(keyPin, LOW);
  BTSerial.begin(9600);
}
void loop()
{
  contact = digitalRead(getData);
  if (contact == HIGH) {
    sensorValue = analogRead(sensorPin);
    double voltage = sensorValue * (5.0 / 1023.0);
    if (BTSerial.available()) {
      Serial.write(BTSerial.read());
    }
    BTSerial.println(voltage, 3);
    BTSerial.write("\r");
    if (Serial.available()) {
      BTSerial.write(Serial.read());
    }
  }
  delay(5);
}

我需要以~200Hz 的频率发送有关测量的数据。 将数据发送到应用程序后,似乎部分数据丢失了。

我尝试了更高的绑定率,但问题仍然存在。有没有一种方法可以使用串行端口从 arduino 发送连续数据而不会丢失部分数据?

我认为问题出在接收器的设计上。我在.net Xamarin中解决了BTL通信,但是原理应该是一样的。在 Android 中,从 InputStream 读取必须快速且不能使用睡眠。您需要使用无限循环并将​​数据快速读取到临时缓冲区中。立即将沙丘字节写入辅助大缓冲区(使用读/写游标),然后,例如,在计时器中处理数据(我想你正在使用一些数据包协议)

        public override void Run()
    {
        WriteLogInfoToLog("ConnectedThread.Run() - before");
        while (true)
        {
            try
            {
                int readBytes = 0;
                lock (InternaldataReadLock)
                {
                    readBytes = clientSocketInStream.Read(InternaldataRead, 0, InternaldataRead.Length);
                    Array.Copy(InternaldataRead, TempdataRead, readBytes);
                }
                if (readBytes > 0)
                {
                    lock (dataReadLock)
                    {
                        dataRead = new byte[readBytes];
                        for (int i = 0; i < readBytes; i++)
                        {
                            dataRead[i] = TempdataRead[i];
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                btlManager.btlState = BTLService.BTLState.Nothing;//Spadlo spojeni, musi spustit cele od zacatku
                WriteLogInfoToLog("ConnectedThread.Run() - EXCEPTION " + e.Message + ", " + e.HResult + ", " + e.StackTrace + ", " + e.InnerException);
                if (e is Java.IO.IOException)
                {
                }
                else
                {
                }
                break;
            }
        }
        WriteLogInfoToLog("ConnectedThread.Run() - after");
    }