使用微信开发者工具编写蓝牙接收8个字节数据的所有文件
在微信开发者工具中编写蓝牙接收8个字节数据的代码,需要创建以下文件:
- index.js:主要的蓝牙接收代码逻辑。
- index.wxml:用于展示蓝牙接收的数据。
- index.wxss:用于设置页面样式。
- project.config.json:项目配置文件。
接下来,按照以下步骤编写这些文件。
- 创建一个新的小程序项目,在项目根目录下创建文件 index.js,编写以下代码:
Page({
data: {
receivedData: '', // 接收到的数据
},
onLoad() {
wx.openBluetoothAdapter({ // 打开蓝牙适配器
success: () => {
this.startBluetoothDevicesDiscovery(); // 开始搜索蓝牙设备
},
fail: (err) => {
console.error(err);
},
});
},
startBluetoothDevicesDiscovery() {
wx.startBluetoothDevicesDiscovery({ // 开始搜索蓝牙设备
success: () => {
this.onBluetoothDeviceFound(); // 监听蓝牙设备发现事件
},
fail: (err) => {
console.error(err);
},
});
},
onBluetoothDeviceFound() {
wx.onBluetoothDeviceFound((res) => { // 监听蓝牙设备发现事件
const devices = res.devices;
const targetDevice = devices.find(device => device.name === 'YourDeviceName'); // 替换成你的设备名称
if (targetDevice) {
this.createBLEConnection(targetDevice); // 连接指定设备
}
});
},
createBLEConnection(device) {
wx.createBLEConnection({ // 连接指定设备
deviceId: device.deviceId,
success: (res) => {
this.startBluetoothDevicesImage(); // 开始接收蓝牙数据
},
fail: (err) => {
console.error(err);
},
});
},
startBluetoothDevicesImage() {
wx.onBLECharacteristicValueChange((res) => { // 监听蓝牙设备数据变化事件
const receivedData = this.ab2hex(res.value);
this.setData({
receivedData: receivedData,
});
});
wx.notifyBLECharacteristicValueChange({ // 启用低功耗蓝牙设备特征值变化时的 notify 功能
state: true,
success: (res) => {
console.log('启用notify功能成功');
},
fail: (err) => {
console.error(err);
},
});
},
ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2);
}
);
return hexArr.join('');
},
});
- 在项目根目录下创建文件 index.wxml,编写以下代码:
<view class="container">
<view class="received-data">{{receivedData}}</view>
</view>
- 在项目根目录下创建文件 index.wxss,编写以下代码:
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.received-data {
font-size: 16px;
color: #333;
}
- 在项目根目录下创建文件 project.config.json,编写以下代码:
{
"miniprogramRoot": "./",
"projectname": "bluetooth-receive",
"description": "蓝牙接收8个字节数据",
"appid": "",
"setting": {
"urlCheck": true,
"es6": true,
"postcss": true,
"minified": true,
"newFeature": true
},
"compileType": "miniprogram",
"scripts": {
"beforeCompile": "miniprogram-compile"
}
}
请注意将上述代码中的 "YourDeviceName" 替换为你要连接的设备的名称。
完成上述步骤后,你可以在微信开发者工具中运行该项目,从蓝牙设备接收8个字节的数据,并在页面上显示接收到的数据
原文地址: https://www.cveoy.top/t/topic/iTQr 著作权归作者所有。请勿转载和采集!