接受数据只要 wx.notifyBLECharacteristicValueChange监听器打开,
wx.onBLECharacteristicValueChange是接受数据的函数。
数据接收到后需要做数据解析
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
这个过程也需要获取接口对应参数:
如何获取请看微信小程序与低功耗蓝牙通信-往硬件端发送数据
deviceId: "2C:AB:33:33:94:08",
serviceId: "0808FF00-0808-0A09-0807-060504030201",
characteristicId:"0808FF01-0808-0A09-0807-060504030201",
微信小程序获取数据:
放在onload函数
onLoad:function(){
console.log("监听hc-09传来的数据")
//打开监听器 获取hc-09发来的数据
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: "2C:AB:33:33:94:08",
serviceId: "0808FF00-0808-0A09-0807-060504030201",
characteristicId:"0808FF01-0808-0A09-0807-060504030201",
success: function (res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
}
})
//hc-09传来的数据解析 转换为字符串
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
//监听hc-09传来的数据
wx.onBLECharacteristicValueChange(function (res) {
console.log('hc-09传来的数据是:', ab2hex(res.value))
var date=ab2hex(res.value)
//根据hc-09传来的数据调手机震动 on==开 off==关
if(date==="on"){
console.log("打开震动")
wx.vibrateLong();
}else{
console.log("关闭震动")
}
})
},