1.前言
微信小程序中连接蓝牙设备,信息写入流程
1、检测当前使用设备(如自己的手机)是否支持蓝牙/蓝牙开启状态
wx:openBluetoothAdapter({})
2、如蓝牙已开启状态,检查蓝牙适配器的状态
wx.getBluetoothAdapterState({})
3、添加监听蓝牙适配器状态变化
wx.onBluetoothAdapterStateChange({})
4、搜索附近蓝牙设备
wx.startBluetoothDevicesDiscovery({})
5、监听搜索的到设备
wx.onBluetoothDeviceFound({})
遍历设备列表找到和macAddr(看自己家的蓝牙装置的物理地址)匹配的设备的deviceId
6、连接想要连接的切匹配成功的设备
wx.createBLEConnection({})
7、获取连接成功的设备的设备服务servicesID
wx.getBLEDeviceServices({})
8、获取设备特征id
wx.getBLEDeviceCharacteristics({})
9、向设备写入指令
wx.writeBLECharacteristicValue({})
以下是代码重点,本人亲测有效,集官网和百家之所长,汇聚之大成,入我门来,使君不负观赏
2. 小程序前端index.wxml
<wxs module="utils">
module.exports.max = function(n1, n2) {
return Math.max(n1, n2)
}
module.exports.len = function(arr) {
arr = arr || []
return arr.length
}
</wxs>
<button bindtap="openBluetoothAdapter" class="primary-btn" >开始扫描</button>
<button bindtap="closeBLEConnection" class="default-btn" >断开连接</button>
<button bindtap="opendeng" class="sumit-btn" >开灯</button>
<button bindtap="guandeng" class="warn-btn" >关灯</button>
<view class="devices_summary">已发现 {
{
devices.length}} 个外围设备:</view>
<scroll-view class="device_list" scroll-y scroll-with-animation>
<view wx:for="{
{devices}}" wx:key="index"
data-device-id="{
{item.deviceId}}"
data-name="{
{item.name || item.localName}}"
bindtap="createBLEConnection"
class="device_item"
hover-class="device_item_hover">
<view style="font-size: 16px; color: #333;">{
{
item.name}}</view>
<view style="font-size: 10px">信号强度: {
{
item.RSSI}}dBm ({
{
utils.max(0, item.RSSI + 100)}}%)</view>
<view style="font-size: 10px">UUID: {
{
item.deviceId}}</view>
<view style="font-size: 10px">Service数量: {
{
utils.len(item.advertisServiceUUIDs)}}</view>
</view>
</scroll-view>
<view class="connected_info" wx:if="{
{connected}}">
<view>
<icon class="icon-box-img" type="success" size="33"></icon>
<view class="icon-box-text"> {
{
name}}连接成功!!!</view>
</view>
</view>
3.小程序index.wxss
page {
color: #333;
}
.icon-box-img{
height: 20px;
float: left;
margin-left: 20%;
}
.icon-box-text{
height: 30px;
line-height: 30px;
margin-left:5px;
float: left;
}
.primary-btn{
margin-top: 30rpx;
/* border: rgb(7, 80, 68) 1px solid; */
color: rgb(241, 238, 238)

本文详细介绍了在微信小程序中如何连接蓝牙设备,包括检测设备支持、开启蓝牙、搜索设备、连接设备以及向设备写入指令的过程。同时提供了关键代码段和注意事项,适用于iOS和Android设备。
最低0.47元/天 解锁文章
2462





