80,351
社区成员
发帖
与我相关
我的任务
分享
String target_address=00:15:83:12:17:86 //下位机蓝牙模块的地址
String uuid = "00001101-0000-1000-8000-00805F9B34FB";
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bluetoothDevice=bluetoothAdapter.getRemoteDevice(target_address);
BluetoothSocket clientSocket;
OutputStream os = null;
InputStream is = null;
new Thread(new Runnable() {
@Override
public void run()
{
try
{
clientSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(uuid));
clientSocket.connect();
is = clientSocket.getInputStream();
os = clientSocket.getOutputStream();
}
catch (IOException e) {e.printStackTrace();}
}
}).start();
//读取来自下位机的内容
new Thread(new Runnable() {
@Override
public void run()
{
try
{
while (true)
{
byte[] buffer = new byte[1024];
int bytes=0;
// Read from the InputStream
if ((bytes = is.read(buffer)) > 0) {
byte[] buf_data = new byte[bytes];
for (int i = 0; i < bytes; i++) {
buf_data[i] = buffer[i];
Log.i("read from MCU :", buf_data[i]+"");}
}
}
}
catch (IOException e) {e.printStackTrace();}
}
}).start();
try {
byte msg=65;
os.write(msg);
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}