我通过蓝牙从Arduino发送整数传感器值,我尝试在我正在编写的Android应用程序中读取这些整数。我试图在文本视图中显示我得到的值,但是当我将设备与蓝牙模块连接并打开应用程序时,没有任何反应。请帮忙
这是Arduino的代码:
#include <SoftwareSerial.h>
SoftwareSerial ble(8, 7); // RX, TX
void setup() {
// Open serial port
Serial.begin(9600);
// Begin bluetooth serial port communication
ble.begin(9600);
}
void loop() {
int sensorValue = analogRead(A0);
Serial.println("Sending Bluetooth Message...");
ble.write(sensorValue);
delay(1000);
}
和我的Android应用的代码:
package com.example.fotini.eog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private BluetoothSocket bt_socket;
private InputStream in_stream;
boolean kill_worker = false;
Handler handler = new Handler();
TextView myLabel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLabel = (TextView)findViewById(R.id.myLabel);
BluetoothAdapter bt_adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bt_device = bt_adapter.getRemoteDevice("60:64:05:D1:34:38");
bt_adapter.cancelDiscovery();
try {
bt_socket = bt_device.createRfcommSocketToServiceRecord(UUID.fromString("00002A00-0000-1000-8000-00805F9B34FB"));
bt_socket.connect();
} catch (IOException e) {
e.printStackTrace();
}
startListeningThread();
}
public void startListeningThread() {
try {
in_stream = bt_socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
Thread worker = new Thread(new Runnable() {
@Override
public void run() {
while(!Thread.currentThread().isInterrupted() && !kill_worker) {
try {
//Read the incoming response
while (in_stream.available() > 0) {
final int readMessage = in_stream.read();
myLabel.setText(readMessage);
handler.post(new Runnable() {
@Override
public void run() {
myLabel.setText(readMessage);
}
});
}
} catch (IOException e) {
kill_worker = true;
}
}
}
});
worker.start();
}