微信小程序蓝牙与MCU 8 字节数组通讯教程
以下是一个示例的微信小程序蓝牙与MCU通讯的程序,包括发送和接收功能,并且有连接蓝牙按钮及连接状态的手机界面。
index.js
const app = getApp();
Page({
data: {
connected: false, // 蓝牙连接状态
devices: [], // 可连接的蓝牙设备列表
deviceId: '', // 已连接的蓝牙设备ID
serviceId: '', // 蓝牙设备的服务ID
characteristicId: '', // 蓝牙设备的特征值ID
receiveData: '', // 接收到的数据
sendText: '' // 要发送的文本
},
// 初始化蓝牙适配器
initBluetooth: function() {
wx.openBluetoothAdapter({
success: (res) => {
console.log('初始化蓝牙适配器成功', res);
this.startBluetoothDevicesDiscovery();
},
fail: (err) => {
console.error('初始化蓝牙适配器失败', err);
}
});
},
// 开始搜索蓝牙设备
startBluetoothDevicesDiscovery: function() {
wx.startBluetoothDevicesDiscovery({
success: (res) => {
console.log('开始搜索蓝牙设备成功', res);
this.onBluetoothDeviceFound();
},
fail: (err) => {
console.error('开始搜索蓝牙设备失败', err);
}
});
},
// 监听搜索到的蓝牙设备
onBluetoothDeviceFound: function() {
wx.onBluetoothDeviceFound((res) => {
res.devices.forEach(device => {
if (!device.name && !device.localName) {
return;
}
const devices = this.data.devices;
const idx = devices.findIndex(item => item.deviceId === device.deviceId);
if (idx === -1) {
devices.push(device);
this.setData({
devices: devices
});
} else {
devices[idx] = device;
this.setData({
devices: devices
});
}
});
});
},
// 连接蓝牙设备
connectBluetoothDevice: function(e) {
const deviceId = e.currentTarget.dataset.deviceid;
wx.createBLEConnection({
deviceId: deviceId,
success: (res) => {
console.log('连接蓝牙设备成功', res);
this.setData({
connected: true,
deviceId: deviceId
});
this.getBLEDeviceServices(deviceId);
},
fail: (err) => {
console.error('连接蓝牙设备失败', err);
}
});
},
// 获取蓝牙设备的服务
getBLEDeviceServices: function(deviceId) {
wx.getBLEDeviceServices({
deviceId: deviceId,
success: (res) => {
console.log('获取蓝牙设备服务成功', res);
res.services.forEach(service => {
if (service.uuid === app.globalData.serviceUUID) {
this.setData({
serviceId: service.uuid
});
this.getBLEDeviceCharacteristics(deviceId, service.uuid);
}
});
},
fail: (err) => {
console.error('获取蓝牙设备服务失败', err);
}
});
},
// 获取蓝牙设备的特征值
getBLEDeviceCharacteristics: function(deviceId, serviceId) {
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId,
success: (res) => {
console.log('获取蓝牙设备特征值成功', res);
res.characteristics.forEach(characteristic => {
if (characteristic.uuid === app.globalData.characteristicUUID) {
this.setData({
characteristicId: characteristic.uuid
});
this.startBLENotifications(deviceId, serviceId, characteristic.uuid);
}
});
},
fail: (err) => {
console.error('获取蓝牙设备特征值失败', err);
}
});
},
// 开启特征值变化监听
startBLENotifications: function(deviceId, serviceId, characteristicId) {
wx.notifyBLECharacteristicValueChange({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
state: true,
success: (res) => {
console.log('开启特征值变化监听成功', res);
this.onBLECharacteristicValueChange();
},
fail: (err) => {
console.error('开启特征值变化监听失败', err);
}
});
},
// 监听特征值变化
onBLECharacteristicValueChange: function() {
wx.onBLECharacteristicValueChange((res) => {
const receiveData = this.data.receiveData + this.ab2str(res.value);
this.setData({
receiveData: receiveData
});
});
},
// 发送数据
sendBLEData: function() {
const sendText = this.data.sendText;
const buffer = this.str2ab(sendText);
const deviceId = this.data.deviceId;
const serviceId = this.data.serviceId;
const characteristicId = this.data.characteristicId;
wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
value: buffer,
success: (res) => {
console.log('发送数据成功', res);
},
fail: (err) => {
console.error('发送数据失败', err);
}
});
},
// ArrayBuffer转字符串
ab2str: function(buffer) {
return String.fromCharCode.apply(null, new Uint8Array(buffer));
},
// 字符串转ArrayBuffer
str2ab: function(str) {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
},
// 断开蓝牙连接
closeBluetoothConnection: function() {
const deviceId = this.data.deviceId;
wx.closeBLEConnection({
deviceId: deviceId,
success: (res) => {
console.log('断开蓝牙连接成功', res);
this.setData({
connected: false,
deviceId: '',
serviceId: '',
characteristicId: '',
receiveData: ''
});
},
fail: (err) => {
console.error('断开蓝牙连接失败', err);
}
});
},
// 清空接收到的数据
clearReceiveData: function() {
this.setData({
receiveData: ''
});
},
// 监听页面加载
onLoad: function() {
this.initBluetooth();
}
});
index.wxml
<view class='container'>
<view class='devices'>
<view wx:for='{{devices}}' wx:key='deviceId'>
<button class='device' wx:if='{{!connected}}' bindtap='connectBluetoothDevice' data-deviceid='{{item.deviceId}}'>{{item.name || item.localName}}</button>
<text class='device' wx:if='{{connected}} && deviceId === item.deviceId'>{{item.name || item.localName}}</text>
</view>
</view>
<view class='status'>
<text class='status-text' wx:if='{{!connected}}'>未连接</text>
<text class='status-text' wx:if='{{connected}}'>已连接</text>
<button class='disconnect-button' wx:if='{{connected}}' bindtap='closeBluetoothConnection'>断开连接</button>
</view>
<view class='receive'>
<text class='receive-title'>接收到的数据:</text>
<text class='receive-data'>{{receiveData}}</text>
<button class='clear-button' bindtap='clearReceiveData'>清空</button>
</view>
<view class='send'>
<input class='send-input' bindinput='inputSendText' placeholder='输入要发送的文本'/>
<button class='send-button' bindtap='sendBLEData'>发送</button>
</view>
</view>
app.js
App({
onLaunch: function () {
// ...
},
globalData: {
serviceUUID: '0000XXXX-0000-1000-8000-00805F9B34FB', // 替换为MCU的服务UUID
characteristicUUID: '0000XXXX-0000-1000-8000-00805F9B34FB' // 替换为MCU的特征值UUID
}
});
app.json
{
'pages': [
'pages/index/index'
],
'window': {
'backgroundTextStyle': 'light',
'navigationBarBackgroundColor': '#fff',
'navigationBarTitleText': '蓝牙与MCU通讯',
'navigationBarTextStyle': 'black'
},
'debug': true
}
app.wxss
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
font-size: 16px;
}
.devices {
margin-bottom: 20px;
}
.device {
display: block;
width: 200px;
height: 40px;
margin: 10px;
background-color: #4CAF50;
color: white;
font-size: 16px;
text-align: center;
line-height: 40px;
border-radius: 4px;
}
.status {
margin-bottom: 20px;
}
.status-text {
font-size: 20px;
}
.disconnect-button {
display: block;
width: 100px;
height: 40px;
margin-top: 10px;
background-color: #f44336;
color: white;
font-size: 16px;
text-align: center;
line-height: 40px;
border-radius: 4px;
}
.receive {
margin-bottom: 20px;
}
.receive-title {
font-size: 20px;
}
.receive-data {
display: block;
width: 300px;
height: 200px;
margin-top: 10px;
background-color: #f2f2f2;
font-size: 16px;
padding: 10px;
overflow: auto;
word-break: break-all;
}
.clear-button {
display: block;
width: 100px;
height: 40px;
margin-top: 10px;
background-color: #f44336;
color: white;
font-size: 16px;
text-align: center;
line-height: 40px;
border-radius: 4px;
}
.send {
margin-bottom: 20px;
}
.send-input {
width: 300px;
height: 40px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
padding: 5px;
}
.send-button {
display: block;
width: 100px;
height: 40px;
margin-top: 10px;
background-color: #4CAF50;
color: white;
font-size: 16px;
text-align: center;
line-height: 40px;
border-radius: 4px;
}
请注意替换 app.js 中的 serviceUUID 和 characteristicUUID 为实际的 MCU 服务 UUID 和特征值 UUID。
这个示例程序中,通过微信开发者工具可以在手机上运行,并且显示可连接的蓝牙设备列表,点击连接按钮可以连接蓝牙设备,连接成功后可以发送文本数据给 MCU,接收到的 MCU 返回的数据也会显示在界面上。
原文地址: https://www.cveoy.top/t/topic/qvlE 著作权归作者所有。请勿转载和采集!