Я пытался получить сигнал от модуля HC-05, подключенного к Arduino Uno.Я шаг за шагом следовал документации BT и не повезло!
Я думаю, что проблема в функциях моего обработчика, поскольку приложение успешно подключается к HC-05.Однако, когда я пытаюсь показать сообщение или отправить строку в Arduino, ничего не появляется, ни ошибок, ни сбоев, ничего.Приложение просто ничего не делает.
Можете ли вы сказать мне, где я ошибся?
public class Bluetooth_Activity extends AppCompatActivity {
// Timer:
private static final long START_TIME_IN_MILLIS = 600000;
private TextView mTextViewCountDown;
private Button mButtonStartPause;
private Button mButtonReset;
private CountDownTimer mCountDownTimer;
private boolean mTimerRunning;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
//widgets
Button b1;
Button b2;
Button b3;
TextView t1;
TextView t2;
// Bluetooth:
String address = null, name = null;
BluetoothAdapter mBluetoothAdapter = null;
BluetoothServerSocket serverSocket;
BluetoothSocket btSocket = null;
Set<BluetoothDevice> pairedDevices;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Handler bluetoothIn;
BluetoothDevice mDevice;
private StringBuilder recDataString = new StringBuilder();
InputStream tmpIn = null;
OutputStream tmpOut = null;
ConnectThread mConnectThread;
ConnectedThread connectedThread = null; String random = null;
static final String TAG = "MY_APP_DEBUG_TAG";
static final int MESSAGE_READ = 0;
static final int MESSAGE_WRITE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_);
b1 = (Button) findViewById(R.id.button1);
mButtonReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetTimer();
}
});
updateCountDownText();
// **********************************************BLUETOOTH FUNCTIONS STARTS ************************************
// 1)determine if the Android device supports Bluetooth.
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
// 2)determine if Bluetooth is enabled, and if it is not enabled, to enable it.
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
// 4)retrieve the actual Bluetooth device it will communicate with, in this case the Arduino’s hc-05 module.
// Android’s currently-paired devices into a storage structure called a “Set”.
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
mDevice = device;
}
}
mConnectThread = new ConnectThread(mDevice);
mConnectThread.start();
// Write to Socket:
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String random = "App is sending a text";
connectedThread.write(random.getBytes());
}
});
}
// 5)form the connection between the Android and the Arduino on separate thread.
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
mmSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) {
}
return;
}
// mConnectedThread = new MyBluetoothService.ConnectedThread(mmSocket);
// mConnectedThread.start();
connectedThread= new ConnectedThread(mmSocket);
connectedThread.start();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
// Log.e(TAG, "Could not close the connect socket", e);
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private byte[] mmBuffer;
Button b1 = (Button) findViewById(R.id.button1);
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams; using temp objects because
// member streams are final.
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
mmBuffer = new byte[1024];
int numBytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
while (true) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
handler.obtainMessage(MESSAGE_READ, numBytes, -1,
mmBuffer).sendToTarget();
} catch (IOException e) {
Log.d(TAG, "Input stream was disconnected", e);
break;
}
}
}
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "Error occurred when sending data", e);
}
}
// Call this method from the main activity to shut down the connection.
public void cancel () {
try {
mmSocket.close();
} catch (IOException e) {
// Log.e(TAG, "Could not close the connect socket", e);
}
}
}
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 1:
byte[] Readbuf = (byte[]) msg.obj;
String tempMsg = new String(Readbuf,0,msg.arg1);
Toast.makeText(getApplicationContext(), "OutPut Recived From Bluetooth : \n" + tempMsg,
Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});