本文将详细介绍微信小程序的蓝牙开发流程(附源码)
准备:
微信只支持低功耗蓝牙也就是蓝牙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) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
}
})
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
wx.onBLECharacteristicValueChange(function (res) {
console.log('characteristic value comed:', ab2hex(res.value))
})
这里第一个函数是开启notify服务,deviceId、serviceId、characteristicId都是之前我们获取的,第二个函数是将bufferArray类型转为string类型,因为buffer不能直接在console.log里输出,会显示null,第三个函数就是监听蓝牙发送过来的值了,蓝牙每次发送一个值,都会回调这个函数,res.value就是一个bufferArray类型,存的是发送过来的值

7.写数据到蓝牙

let buffer = new ArrayBuffer(3)
let dataView = new DataView(buffer)
dataView.setUint8(1, 100)

wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
value: buffer,
success: function (res) {
console.log('writeBLECharacteristicValue success', res.errMsg)
}
})
传数据给蓝牙时只能用buffer类型,let buffer = new ArrayBuffer(3)这句话定义一个三个长度的buffer,dataView.setUint8(1, 100)这句话将第一个值设置为100,所以传递过去的值就是00 64 00 (十六进制)

附录(直接复制粘贴就能运行)

JS源码:

var app = getApp();
var deviceId;
var i=0;
var serviceId=[];
var characteristicId=[];
Page({
data: {

},
onLoad:function(){
wx.onBluetoothAdapterStateChange(function (res) {
console.log('adapterState changed, now is', res)
})

},

openadapter:function(){
wx.openBluetoothAdapter({
success: function(res) {
console.log(res,"success")
},
fail: function (res) {
console.log(res,"fail")
},
})
// wx.getBluetoothAdapterState({
// complete: function (res) {
// console.log("currentstate:",res)
// }
// })
},
closeadapter: function () {
wx.closeBluetoothAdapter({
success: function (res) {
console.log(res, "success")
},
fail: function (res) {
console.log(res, "fail")
},
})
// wx.getBluetoothAdapterState({
// complete: function (res) {
// console.log("currentstate:", res)
// }
// })
},

opendiscovery:function(){
wx.startBluetoothDevicesDiscovery({
services: [],
success: function (res) {
console.log(res)
},
fail: function (res) {
console.log(res, "fail")
},
})
},

closediscovery:function(){
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
console.log(res)
},
fail: function (res) {
console.log(res, "fail")
},
})
},

getdevice:function(){
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
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++;
}
}
})
},

getconnecteddevice:function(){
wx.getConnectedBluetoothDevices({
//services:[],
success: function (res) {
console.log(res)
}
})
},
connecteddevice:function(){
wx.createBLEConnection({
deviceId: deviceId,
success: function(res) {
console.log(res);
},
})
},
getservice:function(){
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++;
}
},
})
},
getcharacteristics:function(){
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId[0],
success: function (res) {
console.log('device getBLEDeviceCharacteristics:', res.characteristics)
}
})
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++;
}
}
})
},
startread:function(){
wx.readBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
success: function (res) {
console.log('readBLECharacteristicValue:', res.errCode)
}
})
},
startnotify:function(){
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
success: function (res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
}
})
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
wx.onBLECharacteristicValueChange(function (res) {
console.log('characteristic value comed:', ab2hex(res.value))
})
},
startwrite:function(){
let buffer = new ArrayBuffer(3)
let dataView = new DataView(buffer)
dataView.setUint8(1, 100)

wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
value: buffer,
success: function (res) {
console.log('writeBLECharacteristicValue success', res.errMsg)
}
})
}

})

WXML源码:

<button bindtap='openadapter'>打开适配器</button>
<button bindtap='closeadapter'>关闭适配器</button>
<button bindtap='opendiscovery'>开始搜索</button>
<button bindtap='closediscovery'>关闭搜索</button>
<button bindtap='getdevice'>获取设备</button>
<button bindtap='getconnecteddevice'>获取已连接设备</button>
<button bindtap='connecteddevice'>连接我的设备</button>
<button bindtap='getservice'>获取服务</button>
<button bindtap='getcharacteristics'>获取特征值</button>
<button bindtap='startread'>读取值</button>
<button bindtap='startnotify'>开启notify</button>
<button bindtap='startwrite'>写数据</button>

微信小程序之蓝牙开发(详细读数据、写数据、附源码)的更多相关文章

  1. 微信小程序中如何使用WebSocket实现长连接(含完整源码)

    本文由腾讯云技术团队原创,感谢作者的分享. 1.前言   微信小程序提供了一套在微信上运行小程序的解决方案,有比较完整的框架.组件以及 API,在这个平台上面的想象空间很大.腾讯云研究了一番之后,发现 ...

  2. 微信小程序调用蓝牙功能控制车位锁

    第一次学用微信小程序,项目需要,被逼着研究了一下,功能是调用微信小程序的蓝牙功能,连接上智能车位锁,控制升降,大概步骤及调用的小程序接口API如下: 1.打开蓝牙模块 wx.openBluetooth ...

  3. 微信小程序的功能开发工具跟公众号的差别,小程序是一种减负思维对简单APP是巨大打击

    微信小程序的功能开发工具跟公众号的差别,小程序是一种减负思维对简单APP是巨大打击 摘要: 小程序和公众号最大的区别有如下四点:1.小程序没有粉丝,开发者在后台能看到的只能是累计用户访问数以及实时统计 ...

  4. 利用python实现微信小程序游戏跳一跳详细教程

    利用python实现微信小程序游戏跳一跳详细教程 1 先安装python 然后再安装pip <a href="http://newmiracle.cn/wp-content/uploa ...

  5. 微信小程序--使用云开发完成支付闭环

    微信小程序--使用云开发完成支付闭环 1.流程介绍 2. 代码实现和逻辑思想描述 云函数统一下单 对应云函数 unipay [CloudPay.unifiedOrder] 函数思路 : 调用云函数封装 ...

  6. Slog71_选取、上传和显示本地图片GET !(微信小程序之云开发-全栈时代3)

    ArthurSlog SLog-71 Year·1 Guangzhou·China Sep 12th 2018 ArthurSlog Page GitHub NPM Package Page 掘金主页 ...

  7. openlayers5-webpack 入门开发系列结合 echarts4 实现散点图(附源码下载)

    前言 openlayers5-webpack 入门开发系列环境知识点了解: node 安装包下载webpack 打包管理工具需要依赖 node 环境,所以 node 安装包必须安装,上面链接是官网下载 ...

  8. 基于微信小程序的系统开发准备工作

    腾讯推出微信小程序也有一段时间了,在各种行业里面也都掀起一阵阵的热潮,很多APP应用被简化为小程序的功能迅速推出,同时也根据小程序的特性推出各种独具匠心的应用,相对传统的APP来说,微信小程序确实能够 ...

  9. 微信小程序之蓝牙 BLE 踩坑记录

    前言 前段时间接手了一个微信小程序的开发,主要使用了小程序在今年 3 月开放的蓝牙 API ,此过程踩坑无数,特此记录一下跳坑过程.顺便开了另一个相关的小项目,欢迎 start 和 fork: BLE ...

随机推荐

  1. node 文件、文件夹 增删改查

    1. 文件夹 增加文件夹 var fs = require("fs"); console.log("创建目录 tmp"); fs.mkdir("tmp ...

  2. jq 插入结构

    一.插入 1. append $("#div").append('<a href="baidu.com">a</a>') ;   // ...

  3. 算法笔记--2-sat

    强连通分量的应用,详见<挑战程序设计>P324 例题1:HDU Peaceful Commission 思路:强连通分量分解,看有没有两个同一个国家的代表在一个强连通分量里,如果有,就是N ...

  4. Codeforces 140D - New Year Contest

    140D - New Year Contest 思路:贪心+排序.罚时与时间成正比,因为在0点前做完的题都可以在0点提交.从时间短的开始做最优. 代码: #include<bits/stdc++ ...

  5. Vue.js 响应式原理

    1. Vue2.x 基于 Object.defineProperty 方法实现响应式(Vue3 将采用 Proxy) Object.defineProperty(obj, prop, descript ...

  6. LeetCode--225--用队列实现栈

    问题描述: 使用队列实现栈的下列操作: push(x) -- 元素 x 入栈 pop() -- 移除栈顶元素 top() -- 获取栈顶元素 empty() -- 返回栈是否为空 注意: 你只能使用队 ...

  7. P4721 【模板】分治 FFT

    其实是分治ntt,因为fft会爆精度,真*裸题 分治过程和fft的一模一样,主要就是ntt精度高,用原根来代替fft中的\(w_n^k\) 1.定义:设m>1,(a,m)==1,满足\(a^r= ...

  8. Tips for Sync Vimtex and PDF

    vimtex synctex: \lv. skim synctex: to display the TeX source line corresponding to a point in the PD ...

  9. 安装torch-opencv

    安装torch-opencv torch torch-opencv opencv-3.1.0 opencv-contrib 想在torch中使用光流法,于是就希望能够调用opencv中的光流代码,而t ...

  10. FREETEXTBOX

    本文转自http://blog.csdn.net/JOHNCOOLS/archive/2006/04/08/655553.aspx感谢作者们的付出---------------版本: FreeText ...