You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Web BLE获取小米手环心率参数?现有HTML代码求问题排查

小米手环2 BLE心率读取代码问题排查

核心错误点

  • 设备名配置错误
    目标设备为小米手环2,但代码中deviceName变量赋值为'Mi Smart Band 5',对应小米手环5,会导致扫描过滤阶段无法找到目标设备,需要修改为小米手环2的对应广播名,一般为'MI Band 2'。
  • 缺少心率传感器启动逻辑
    小米手环2的实时心率测量需要手动触发:在获取到心率服务(0x180d)后,需找到UUID为00002a39-0000-1000-8000-00805f9b34fb的心率控制特征,向该特征写入0x01字节才能启动传感器测量,当前代码没有该步骤,仅开启心率特征通知不会收到数据推送。
  • 心率值解析错误
    标准心率特征0x2a37的返回值中,第1个Uint8为标志位,第2个Uint8才是实际心率值,当前handleChangedValue函数直接取getUint8(0)作为心率值,解析逻辑错误;同时日志打印为UV Index属于示例代码残留,需要修改为对应心率输出。
  • 冗余的主动读取逻辑
    实时心率数据为设备主动推送的通知类型,不需要主动调用readValue方法读取,当前read函数中的主动读取逻辑属于无效操作,且会触发无意义报错。
  • 绑定适配要求
    小米手环2需要先在系统蓝牙设置中完成配对绑定,才能正常访问GATT心率服务,未绑定状态下连接会被拒绝。

核心代码修正示例

// 1. 修改设备名,新增心率控制特征UUID
var deviceName = 'MI Band 2'
var bleHeartRateControlChar = '00002a39-0000-1000-8000-00805f9b34fb'

// 2. connectGATT函数中新增启动传感器逻辑
function connectGATT() {
  if (bluetoothDeviceDetected.gatt.connected && gattCharacteristic) {
    return Promise.resolve()
  }
  return bluetoothDeviceDetected.gatt.connect()
  .then(server => {
    console.log('Getting GATT Service...')
    return server.getPrimaryService(bleService)
  })
  .then(service => {
    console.log('Getting GATT Characteristic...')
    // 先获取心率控制特征,写入0x01启动测量
    return service.getCharacteristic(bleHeartRateControlChar)
    .then(controlChar => {
      return controlChar.writeValue(new Uint8Array([0x01]))
    })
    // 再获取心率测量特征
    .then(() => service.getCharacteristic(bleCharacteristic))
  })
  .then(characteristic => {
    gattCharacteristic = characteristic
    gattCharacteristic.addEventListener('characteristicvaluechanged',
        handleChangedValue)
    document.querySelector('#start').disabled = false
    document.querySelector('#stop').disabled = true
  })
}

// 3. 修正解析逻辑
function handleChangedValue(event) {
  // 第2个字节为心率值
  let heartRate = event.target.value.getUint8(1)
  var now = new Date()
  console.log('> ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + ' 心率为 ' + heartRate)
}

内容的提问来源于stack exchange,提问作者Sowmya Kannan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:36:09