我正在制作一个项目,arduino uno将向android发送数据,并且我将接收到的数据记录在Logcat Android Studio中。 InputStream确实从arduino收到了一些内容,但无法正确转换为字符串。
对于android代码,我几乎完全遵循本教程(https://github.com/mitchtabian/Sending-and-Receiving-Data-with-Bluetooth/blob/master/Bluetooth-Communication/app/src/main/java/com/example/user/bluetooth_communication/BluetoothConnectionService.java)
我没有包含AcceptThread和OutputStream代码,因为该应用程序仅设计用于接收来自arduino的数据。以下是arduino代码,它用于发送从传感器测得的温度。
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
try {
tmpIn = mmSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
}
public void run(){
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
int temp;
SoftwareSerial BTSerial(2,3);
void setup(){
BTSerial.begin(9600);
Serial.begin(9600);
}
void loop(){
temp = analogRead(A0);
Serial.print("Temperature: ");
Serial.print(temp);
Serial.print("*C");
Serial.println();
delay(1000);
BTSerial.print(temp);
BTSerial.print('\n');
}
字符串如下:
05-19 19:50:20.097 15758-16275 / com.example.graphreader D / BluetoothConnection:ConnectedThread:正在启动。 05-19 19:50:20.232 15758-16281 / com.example.graphreader D / BluetoothConnection:InputStream:�����������
我尝试打印接收到的整数,它可以工作,但与我从Arduino串行监视器获得的读数不同。