HC-06将数据发送到Android

时间:2017-11-18 05:53:39

标签: android bluetooth arduino android-bluetooth arduino-uno

我正在使用Android设备开展Arduino项目。但是我们遇到了一个小问题。

我们希望将PPG传感器值发送到Android设备并在UI中显示。我们设法与蓝牙连接。但我们无法在Android设备中接收数据。

(我们使用带有HC-06蓝牙模块的Arduino Uno板。)

Arduino代码:

#include <SoftwareSerial.h>
#define pinRX 12 //rx pin num
#define pinTX 13 //tx pin num 
SoftwareSerial BTSerial(pinRX, pinTX);

byte buffer[1024];
int bufferPosition;
const int analogInPin = A1;
int outputValue = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("Hello!");
  BTSerial.begin(9600);
}

void loop() {
  //ppg sensor
  int sensorValue = analogRead(analogInPin);
  Serial.println(sensorValue);
  Serial.write(sensorValue);
  delay(1000);
}

Android代码:

//create new class for connect thread
private class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    //creation of the connect thread
    public ConnectedThread(BluetoothSocket socket) {
      InputStream tmpIn = null;
      OutputStream tmpOut = null;
      try {
        //Create I/O streams for connection
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
        Log.i("TEST", "TESTRTETE ::  Thread :: " + tmpIn);
      } catch (IOException e) {
      }
      mmInStream = tmpIn;
      mmOutStream = tmpOut;
    }

    public void run() {
      byte[] buffer = new byte[256];
      int bytes;
      int i;
      // Keep looping to listen for received messages
      while (true) {
        try {
          Log.i("TEST", "TESTRTETE ::  run() " + mmInStream.available());
          bytes = mmInStream.read(buffer);
          Log.i("TEST", "TESTRTETE ::  bytes = " + bytes);//read bytes from input buffer
          String readMessage = new String(buffer, 0, bytes);
          // Send the obtained bytes to the UI Activity via handler
          Log.i("TEST", "TESTRTETE ::  readMSG ::  " + readMessage + "");
          bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
        } catch (IOException e) {
          Log.i("TEST", "TESTRTETE :: error :: ");
          break;
        }
      }
    }

线程运行良好......但我们不知道它为什么会发生IOException。

11-18 14:48:04.421 27950-27950/com.example.sonminhee.bttest I/TEST: TESTRTETE :: btSocket :: 
11-18 14:48:05.461 27950-27950/com.example.sonminhee.bttest I/TEST: TESTRTETE :: thread.connect() :: 
11-18 14:48:05.466 27950-27950/com.example.sonminhee.bttest I/TEST: TESTRTETE ::  Thread :: android.bluetooth.BluetoothInputStream@2ea790e7
11-18 14:48:05.466 27950-27950/com.example.sonminhee.bttest I/TEST: TESTRTETE :: thread.start() :: 
11-18 14:48:05.466 27950-9233/com.example.sonminhee.bttest I/TEST: TESTRTETE ::  run() 0

这是Android日志。

从Android接收数据似乎存在问题。 请给我任何解决方案。谢谢!

0 个答案:

没有答案