最近在使用uniapp写小程序蓝牙时遇到个奇怪的问题,我可以向esp32 c3 设备蓝牙发送信息他能准确收到数据,而设备发过来的蓝牙我打印出来是空

在查阅资料的时候发现,需要将value 转换成16进制才能正确的显示下面是代码

/**  
			 * 订阅操作成功后需要设备主动更新特征值的 value,才会触发 uni.onBLECharacteristicValueChange 回调。  
			 */
			notifyBLECharacteristicValueChange() {
				let that = this
				wx.notifyBLECharacteristicValueChange({
					"state": true, // 启用 notify 功能  
					"deviceId": this.deviceId,
					"serviceId": this.serviceId,
					"characteristicId": this.characteristicId,
					success(res) {
						console.log('notifyBLECharacteristicValueChange success:' + res.errMsg);
						// ArrayBuffer转16进度字符串示例
						function ab2hex(buffer) {
							const hexArr = Array.prototype.map.call(
								new Uint8Array(buffer),
								function(bit) {
									return ('00' + bit.toString(16)).slice(-2)
								}
							)
							return hexArr.join('')
						}
						uni.onBLECharacteristicValueChange(function(res) {
							console.log('uni.onBLECharacteristicValueChange');
							var value = ab2hex(res.value);

							console.log("ArrayBuffer转16进度字符串完成:" + value)
						});
					},
					fail(e) {
						console.log('启用 notify 功能失败,错误码:' + e.errCode);
					}
				});
			},

这是转换后获取的数据,设备会自动回复16进制的1.2.3.4.5.6

更多推荐