如何初始化BLE设备并向Arduino的BLE模块发送字符串?
如何向Arduino BLE模块发送字符串数据?
嘿,既然你已经通过Gatt = myDevice.connectGatt(this, true, gattCallback);成功建立了和BLE模块的连接,接下来要发送字符串其实分几步就能搞定,我给你捋清楚:
1. 找到对应BLE服务和可写特征
BLE通信是基于**服务(Service)和特征(Characteristic)**的,你得先定位到Arduino模块上专门用来接收数据的那个特征(它必须具备WRITE权限)。这一步要在BluetoothGattCallback的onServicesDiscovered回调里处理——因为连接成功后,我们需要先发现设备提供的所有服务。
示例代码如下:
private BluetoothGattCharacteristic writeCharacteristic; // 重写Gatt回调中的服务发现方法 @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); if (status == BluetoothGatt.GATT_SUCCESS) { // 替换成你的Arduino BLE服务UUID(要和Arduino端代码一致) BluetoothGattService targetService = gatt.getService(UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb")); if (targetService != null) { // 替换成你的可写特征UUID(同样要和Arduino端匹配) writeCharacteristic = targetService.getCharacteristic(UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb")); if (writeCharacteristic != null) { // 确认这个特征支持WRITE操作 if ((writeCharacteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) { // 特征准备就绪,接下来就可以发数据啦 } } } } }
2. 将字符串转换为字节数组
BLE特征只能接收字节数据,所以我们需要把要发送的字符串转成字节数组,通常用UTF-8编码(和Arduino端解码保持一致):
String sendMessage = "Hello Arduino!"; // 用UTF-8编码转成字节数组 byte[] sendData = sendMessage.getBytes(StandardCharsets.UTF_8);
3. 向特征写入数据
拿到字节数组后,就可以调用Gatt的写入方法了。这里要注意设置写入类型:
WRITE_TYPE_NO_RESPONSE:不需要模块回复,速度更快,适合不需要确认的场景WRITE_TYPE_DEFAULT:需要模块返回确认,适合确保数据送达的场景
示例代码:
if (writeCharacteristic != null && Gatt != null) { // 设置要写入的字节数据 writeCharacteristic.setValue(sendData); // 选择写入类型,这里以无响应为例 writeCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); // 发送写入请求 boolean writeSuccess = Gatt.writeCharacteristic(writeCharacteristic); if (writeSuccess) { // 写入请求已成功发送 } else { // 写入请求失败,检查连接状态或特征是否正确 } }
4. (可选)监听写入结果
如果用了WRITE_TYPE_DEFAULT,可以在Gatt回调里重写onCharacteristicWrite来确认数据是否真的写入成功:
@Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); if (status == BluetoothGatt.GATT_SUCCESS) { // 数据成功写入Arduino模块 } else { // 写入失败,处理错误(比如重连后重试) } }
几个关键注意点
- UUID匹配:Android端用的服务和特征UUID,必须和Arduino BLE代码里定义的完全一致,否则找不到对应特征
- 权限问题:Android 12及以上需要申请
BLUETOOTH_CONNECT权限;低版本需要BLUETOOTH和BLUETOOTH_ADMIN权限,扫描设备还需要定位权限 - 连接状态:写入前一定要确认Gatt连接处于活跃状态,避免空指针异常
内容的提问来源于stack exchange,提问作者Jooonni
相关产品推荐
相关产品推荐

