微信小程序之蓝牙开发(详细读数据、写数据、附源码)

本文将详细介绍微信小程序的蓝牙开发流程(附源码)

准备:

微信只支持低功耗蓝牙也就是蓝牙4.0,普通的蓝牙模块是用不了的,一定要注意。

蓝牙可以连TTL接到电脑上,再用XCOM调试

一开始定义的变量

var deviceId;

var i=0;

var serviceId=[];

var characteristicId=[];

 

蓝牙开发流程:

1.打开蓝牙适配器

2.搜索周围蓝牙

3.获取搜索过程中所搜索到的设备信息

4.连接想要连接的设备

5.获取服务、特征值

6.写数据、读数据

 

具体实现:

1.打开蓝牙适配器

 

wx.openBluetoothAdapter({

success: function(res) {

console.log(res,"success")

},

fail: function (res) {

console.log("fail")

},

})

 

2.适配器打开后可以开始搜索蓝牙设备了

 

wx.startBluetoothDevicesDiscovery({

services: [],

success: function (res) {

console.log(res)

},

fail: function (res) {

console.log("fail")

},

})

    sevices里不要填参数,要不然只能搜索特定的设备

3.搜索一小段时间后可以查看搜索到的设备,一般时间很短,1s都不用,搜不到可以多等等

 

wx.getBluetoothDevices({

success: function (res) {

console.log(res)

i=0;

while (res.devices[i]) {

console.log(i);

console.log(res.devices[i].name,res.devices[i].deviceId);

if(res.devices[i].name=='YahBoom_BL'){

deviceId=res.devices[i].deviceId;

console.log(deviceId);

}

i++;

}

}

})

这一步将所有搜索到的设备的名字和ID输出,并将名字为'YahBoom_BL'的设备的Id存到deviceId里去,这个设备就是我所需要使用的

 

4.现在我们可以获取一个特定设备的所有服务了

 

wx.getBLEDeviceServices({

deviceId: deviceId,

success: function(res) {

console.log(res.services);

i=0;

while(res.services[i]){

serviceId[i]=res.services[i].uuid;

console.log(serviceId[i]);

i++;

}

},

})

这一步我们获取YahBoom_BL的所有服务并储存到serviceId数组里去

5.现在我们可以针对一个特定服务查看这个服务所支持的操作

 

wx.getBLEDeviceCharacteristics({

deviceId: deviceId,

serviceId: serviceId[1],

success: function (res) {

i=0;

while(res.characteristics[i]){

characteristicId[i]=res.characteristics[i].uuid;

console.log(characteristicId[i]);

i++;

}

}

})

在这里我们获取YahBoom_BL的第二个服务(第一个服务下标为0,选第二个因为我的设备的第二个服务的第一个特征值支持notif、read、write,可以把一个服务的所有特征值打印出来查看)的特征值,并将特征值ID存到characteristicId数组里去

 

6.开启notify并读取蓝牙发过来的数据,开启这个后我们就能实时获取蓝牙发过来的值了

 

wx.notifyBLECharacteristicValueChange({

state: true,

deviceId: deviceId,

serviceId: serviceId[1],

characteristicId: characteristicId[0],

success: function (res) {

评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值