【发布时间】:2019-11-27 04:34:35
【问题描述】:
我正在为我的 arduino 传感器做一个应用程序,我想知道如何通过蓝牙实际从 arduino 获取数据到 android studio,因为在我的 arduino 中我输入了Serial.println("occupied"),但是当在 android 中接收时它以某种方式与一些数字混合/像“o2cuppied”这样的字节,否则它将在logcat中单独接收。不知道有什么问题。
Arduino 代码:
void setup() {
serial1.begin(9600); //for the bluetooth module
}
void loop() {
//send data to Bluetooth module//
if (dist[0] < dist_threshold) {
serial1.print("Occupied\n");
}
if (dist[1] < dist_threshold) {
serial1.print("Occupied2\n");
}
安卓
@Override
protected void onCreate(Bundle savedInstanceState) {
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECEIVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
// and clear
txtArduino.setText("Data from Arduino: " + strIncom);
break;
}
}
};
}
private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
bluetoothSocket = socket;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
h.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
}
Logcat
2019-11-27 12:28:13.505 12733-12893/com.example.fyp D/MainActivity: InputStream: O
2019-11-27 12:28:13.508 12733-12893/com.example.fyp D/MainActivity: InputStream: ccupied
【问题讨论】:
标签: android arduino android-bluetooth