android单片机与蓝牙模块通信实例代码
时间: 2023-05-17 16:00:47 浏览: 126
Android串口蓝牙模块的使用.rar_Android串口_msp430_串口_单片机msp_蓝牙模块
将Android单片机与蓝牙模块连接起来,可以实现通过蓝牙模块发送和接收数据,下面是一个实例代码。
首先,需要在Android设备上打开蓝牙,并扫描周围的蓝牙设备。
```java
// 打开蓝牙
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Log.e("TAG", "该设备不支持蓝牙");
} else {
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// 扫描蓝牙设备
private void searchBluetooth() {
mBluetoothAdapter.startDiscovery();
// 注册广播接收器
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
// 广播接收器
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 获取蓝牙设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device != null) {
Log.d("TAG", "发现蓝牙设备:" + device.getName() + " " + device.getAddress());
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mBluetoothAdapter.cancelDiscovery();
}
}
};
```
然后,在Android设备上选择要连接的蓝牙设备,并进行连接操作。
```java
private void connectBluetooth() {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
mBluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
try {
mBluetoothSocket.connect();
Log.d("TAG", "连接成功");
} catch (IOException e) {
Log.e("TAG", "连接失败:" + e.getMessage());
}
}
```
接下来,就可以开始进行数据的发送和接收操作了。
```java
// 发送数据
private void sendBluetooth(String data) {
if (mBluetoothSocket != null) {
try {
OutputStream outputStream = mBluetoothSocket.getOutputStream();
outputStream.write(data.getBytes());
} catch (IOException e) {
Log.e("TAG", "发送失败:" + e.getMessage());
}
}
}
// 接收数据
private void receiveBluetooth() {
if (mBluetoothSocket != null) {
try {
InputStream inputStream = mBluetoothSocket.getInputStream();
byte[] buffer = new byte[1024];
int len;
StringBuilder sb = new StringBuilder();
while ((len = inputStream.read(buffer)) != -1) {
sb.append(new String(buffer, 0, len));
}
Log.d("TAG", "接收到数据:" + sb.toString());
} catch (IOException e) {
Log.e("TAG", "接收失败:" + e.getMessage());
}
}
}
```
以上就是一个Android单片机与蓝牙模块通信的实例代码。需要注意的是,在实际使用中,可能会存在多线程操作等问题,需要根据具体的情况进行调整。
阅读全文