我正在为我的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.println("Occupied");
}
Android
@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
int img = Integer.valueOf(incomingMessage);
Log.d(TAG, "Integer: " + img);
if(img== 1){
mValueView1.setBackgroundColor(Color.RED);
}
} 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:占用
private StringBuilder sb = new StringBuilder();
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length());
final String finalSbprint = sbprint;
TCP:您必须串联传入的字节。