使用通过蓝牙从Arduino收到的数据

时间:2017-10-28 20:32:41

标签: android bluetooth arduino

我正在开发一款Android应用程序,该应用程序将不断从Arduino HC-05接收数据并将其存储在数据库中。现在我专注于正确接收数据(所以只需在屏幕上显示它就是我的下一步)。

我已按照this guide(PDF)设置了一个将从Arduino接收数据的基本应用。但是,它不包括有关使用接收数据的部分。我已经尝试在handleMessage函数中添加两行代码以便在屏幕上显示接收的数据,但我没有看到textview中的任何差异(它保持“Hello World!”)。

我知道我的Arduino发送的数据很好,因为在另一个名为“串行蓝牙终端”的应用程序中它正确显示。以下是Handler类的代码:

Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        byte[] writeBuf = (byte[]) msg.obj;
        int begin = (int)msg.arg1;
        int end = (int)msg.arg2;

        switch(msg.what) {
            case 1:
                String writeMessage = new String(writeBuf);
                writeMessage = writeMessage.substring(begin, end);
                // 2 lines of code I've added here:
                TextView tempTextView = (TextView) findViewById(R.id.text_view);
                tempTextView.setText(writeMessage);
                break;
        }
    }
};

除了2行之外,代码基本上与指南的最后阶段相同。这里是Arduino的代码(目前只是反复发送“1 2.00 3.00”):

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(0, 1); //RX|TX
int Temp=  1;
float Ph = 2;
float Ec = 3;
void setup() {
  Serial.begin(9600);
  BTSerial.begin(9600);
}

void loop() {
  Serial.print(Temp);
  Serial.print(" ");
  delay(100);
  Serial.print(Ph);
  Serial.print(" ");
  delay(100);
  Serial.print(Ec);
  Serial.print(" ");
  delay(100);
  Serial.print('\n');
  if(Serial.available())
    BTSerial.write(Serial.read());
}

0 个答案:

没有答案