微信蓝牙小程序,连接蓝牙模块收发数据。遇到的问题:我连接成功之后发现服务值下面两个特征值一个只能读一个只能写,然后点击读的那个一直收到同一个字,点击发送无论发什么内容只能收到同一个中文字,求指导

新手小程序开发者在尝试通过蓝牙模块进行数据传输时遇到问题,怀疑如何结合两个只能读写的特征值进行操作,并希望实现双向通信。描述了代码片段和遇到的具体问题点。
摘要由CSDN通过智能技术生成

大家好,我是小程序初学者,目前尝试做一个蓝牙小程序连接蓝牙模块进行收发数据,遇到了问题求大佬指点

这是代码运行结果:点击能读的特征值就会接收到耀这个字,点击输入框无论发送什么都会接收到肀这个字


遇到的问题:我连接成功之后发现服务值下面两个特征值一个只能读一个只能写,然后点击读的那个一直收到同一个字,点击发送无论发什么内容只能收到同一个中文字,我在想是需要将两个特征值合在一起使用吗?求指导(ps:小程序是跟着b站上面一个博主做的,他是想把手机发送的内容显示到手机上的接受区,我想实现手机发送在串口助手显示,串口助手发送的能在手机小程序接收区显示),以下是代码内容lanya.wxml部分

<!-- <button bindtap="openAdapter">初始化蓝牙模块</button> -->
<!-- <button bindtap="discoverDevices">开始搜寻附近的蓝牙设备</button> -->
<button bindtap="getDevices">获得周边蓝牙设备</button>
<!-- 一个一个遍历准备连接设备:点击设备名称即可链接 -->
<view wx:if="{{showFlage}}" wx:for="{{devices}}" wx:for-item="device" wx:key="key" bindtap="create" data-index="{{index}}">                                                               
    <view style="width: 750rpx;height:100rpx;color:gray;">{{device.name}} {{device.deviceId}}
    </view>
</view>
<view wx:if="{{showFlage1}}">蓝牙设备:{{name}} {{deviceId}}</view>
<view wx:if="{{showFlage1}}">点击下面服务值获得特征值</view>

<!-- 判断是哪个服务值像之前判断是哪个蓝牙设备那样 -->
<view wx:for="{{services}}" wx:for-item="service" wx:key="key" bindtap="choise" data-index="{{index}}">
    <!-- 将它遍历出来,把id提出来-->
        <view wx:if="{{showFlage1}}" style="color: hotpink;">服务值:{{service.uuid}}</view>
</view>

<view wx:if="{{showFlage2}}">点击下面特征值读写数据</view>
<!-- 一个服务值里面有好多特征值,需要数据索引,添加点击事件 -->
<view wx:if="{{showFlage2}}" style="color: blue;" wx:for="{{characteristics}}" wx:for-item="characteristic" wx:key="key" bindtap="select"data-index="{{index}}">
        <view>特征值:{{characteristic.uuid}}  read:{{characteristic.properties.read}} write:{{characteristic.properties.write}}</view>

</view>
<button bindtap="disconnect">断开连接并返回</button>
<!-- 在输入框上面写入提示 -->
<view style="background-color: lightgray;">请输入数据:
<!-- 设置不能刚进入小程序就显示能够输入数据,利用showkeyboard来设置,改变键盘发送按键,并在点击完成时触发-->
<input style="height: 100rpx;width: 750rpx;" focus = "{{showKeyboard}}" confirm-type="send" bindconfirm="sendData" disabled="{{inputKey}}"></input>
</view>
<view>接收到的数据:</view> 
<view>{{showData}}</view>


lanya.js部分:

//将接收到的字符转化为我们发送的数据
function ab2str(buf){
  return String.fromCharCode.apply(null,new Uint16Array(buf));
}
//定义一个全局变量
let revData = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
      discoverFlag:false,
      devices:[],
      deviceId:'',//蓝牙设备id
      serviceId:'',//蓝牙特征对应服务的UUID


      services:[],
      characteristics:[],//特征值的列表
      characteristicId:'',//蓝牙特征的UUID
      showFlage:true,
      name:'',//保存设备的名字
      showFlage1:false,
      showFlage2:false,

      available:true,
      read:false,
      write:false,
      showKeyboard:false,
      inputKey:true,//设置刚开始输入框不起作用,等到点击特征值之后再起作用
      showData:'',
  },

  /**
   * 生命周期函数--监听页面加载
   * 初始化蓝牙模块
   */
  onLoad: function (options) {
    wx.getBluetoothAdapterState({
      success(res){
        console.log(res)
        if(res.available){
          that.setData({
            available:true
          })
        } else{
          that.setData({
            available:false
          })
        }
      }
    })
    if(this.data.available==false){
      wx.showToast({
        title: '请打开蓝牙',
      })
    }
      wx.openBluetoothAdapter({
        success (res) {
          console.log(res)
        }
      })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
      wx.getBluetoothAdapterState({
        success (res) {
          console.log(res)
          
            if(res.available){
              // wx:wx.showToast({
                // title: '蓝牙没有打开',
                that.setData({
                  available:true
                })
            }else{
              that.setData({
                available:false
              })
              
            }
        }
      })
      if(this.data.available==false){
          wx.showToast({
            title: '请打开蓝牙',
          })
      }
      wx.openBluetoothAdapter({
        success (res) {
          console.log(res)
        }
      })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },
  // 初始化蓝牙模块,切记打开蓝牙
  openAdapter(e){
    wx.openBluetoothAdapter({
      success (res) {
        console.log(res)
      }
    })
  },

//搜寻附近蓝牙设备
  getDevices(){
    let that = this
  // 开始监听蓝牙设备之前,先判断discoverflag是不是真的开始搜寻了
  // getDevices(){
  //   let that = this
    wx.startBluetoothDevicesDiscovery({
      services: [],
      success (res) {
        console.log(res)

        function ab2hex(buffer) {
          var hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function(bit) {
              return ('00' + bit.toString(16)).slice(-2)
            }
          )
          return hexArr.join('');
        }
        // 可以搜寻蓝牙设备ok的话这里放置一个标志
        // that.setData({
        //   // 把这个值放在里面,如果他能搜到的话,方便后面使用
        //   discoverFlag:res.isDiscovering
        // })
     
    // 这里要注意先定义discoverflag
    // if(this.data.discoverFlag){
      // ArrayBuffer转16进度字符串示例
      // 监听搜索到蓝牙设备,将新设备一一列出来
      wx.onBluetoothDeviceFound(function(res) {
          console.log(res)
          let devices = res.devices;

          console.log('new device list has founded')
          // console.dir(devices)//打印设备信息,报错不要紧
          console.log(ab2hex(devices[0].advertisData))

          // ArrayBuffer转16进度字符串示例
          wx.getBluetoothDevices({
            success: function (res) {
              console.log(res)
              that.setData({
                devices:res.devices
              })
            }
          })
          //停止搜寻附近的蓝牙外围设备,如果搜寻到四个设备以上就暂停
          if(that.data.devices.length >= 4){
            wx.stopBluetoothDevicesDiscovery({
              success (res) {
                console.log(res)
              }
            })
          }

      })
    // }
        //如果第一个不是空的的话就打印出来,没有必要可以去掉
    }
  })
},
  //连接蓝牙设备
  create(e){
    let that = this
    console.log(e)
    // 将索引放到index里面
    let index = e.currentTarget.dataset.index
    //获取本机蓝牙适配器状态
    wx.getBluetoothAdapterState({
      success (res) {
        console.log(res)
          if(res.available){
            that.setData({
              available:true
            })
          } else {
            that.setData({
              available:false
            })
          }
      }
    })
    if(this.data.available == false){
      wx.showToast({
        title: '请打开蓝牙',
      })
    }

    wx.createBLEConnection({
      deviceId:that.data.devices[index].deviceId,//点击的那条就取哪条
      wx: wx.showLoading({
        title: '连接中',
      }),

      success (res) {
        console.log(res)//成功回调打印出来
        that.setData({
          deviceId:that.data.devices[index].deviceId,//把数据的值存到这里
          name:that.data.devices[index].name,
          showFlage:false,
          showFlage1:true
        })
          //提示连接成功
          wx:wx.hideLoading({
              // title:'已连接',
          })
        // 获取蓝牙低功耗设备所有服务
        wx.getBLEDeviceServices({
          // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立连接
          deviceId:that.data.deviceId,
          success (res) {
            console.log('device services:', res.services)
            //把列表取出来,一定要加this.setData
            that.setData({
              services:res.services
            })  
          }
        })
      }
    })
  },
  // 判定点击的是哪个服务值
  choise(e){
      console.log(e)
      let that = this
      let index = e.currentTarget.dataset.index
      let serviceId = this.data.services[index].uuid

      this.setData({
        serviceId:serviceId,
      })
    // 获取蓝牙低功耗设备某个服务中所有特征
    wx.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立链接
        deviceId:this.data.deviceId,
        // 这里的 serviceId 需要在 wx.getBLEDeviceServices 接口中获取
        serviceId: this.data.serviceId,//成功回调后获得特征值
        success (res) {
          console.log('device getBLEDeviceCharacteristics:', res.characteristics)
          that.setData({
            characteristics:res.characteristics,
            showFlage2:true,
            showFlage1:false,
          })
        }
    })
  },
  disconnect(){
    let that = this
      wx.closeBLEConnection({
        deviceId:this.data.deviceId,
        success (res) {
          console.log(res)
          that.setData({
            showFlage:true,
            showFlage1:false,
            showFlage2:false,
            inputKey:true,//当点击断开连接返回时,输入框禁用状态
          })
        }
      })
  },
  select(e){
    let that = this
    console.log(e)
    // 将index读取出来,index就是点击了哪个特征值
    let index = e.currentTarget.dataset.index
    // 这个id就等于当前数据里面特征值列表,取出来以后放到初始数据里面
    let characteristicId = this.data.characteristics[index].uuid
    // 将获得的特征值数据放入初始数据里面
    this.setData({
      characteristicId:characteristicId,
      // 设置点击特征值之后,输入框才启用
      showKeyboard:true,
      inputKey:false,//当一点击某个特征值就会往里面的写数据变为false

    })
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId:this.data.deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId:this.data.serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId:this.data.characteristicId,
      success (res) {
        console.log('notifyBLECharacteristicValueChange success', res.errMsg)
        // ArrayBuffer转16进制字符串示例
        function ab2hex(buffer) {
          let hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function(bit) {
              return ('00' + bit.toString(16)).slice(-2)
            }
          )
          return hexArr.join('');
        }
        //监听变化
        wx.onBLECharacteristicValueChange(function(res) {
          console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
          console.log('ArrayBuffer转16进制字符串',ab2hex(res.value))
          var resValue = new Uint8Array(res.value,0);
          console.log('ArrayBuffer转Uint8Array',resValue)
          console.log(ab2hex(res.value))
          console.log(ab2str(res.value))//利用这个方法将接收到的字符转化过来
          let value = ab2str(res.value)
          // 为了防止后面的值覆盖前面接受到的值,需要定义一个全局变量
          //将值累加起来,不让覆盖
          revData += value
          //设置叠加是有限的,不能无底线叠加,意思是清空之前叠加的数据,将最后叠加后的数据赋值给他
          if(revData.length>=30){
            revData = value
          }
          that.setData({
            showData: revData
           
          })
        })
      }
    })
  },
  sendData(e){
    console.log(e)
    //将输入的值给取出来
    let value = e.detail.value
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(value.length)//改成输入这串字符的长度
    let dataView = new DataView(buffer)
    //设置一个循环,一个一个字符来处理,因为我们可能不止发送一个值
    for(let i = 0;i < value.length;i++){
    dataView.setUint8(i, value[i].charCodeAt())//字符转换成Ascii码
    }
    dataView.setUint8(0, 0)

    wx.writeBLECharacteristicValue({
      // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId:this.data.deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId:this.data.serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId:this.data.characteristicId,
      // 这里的value是ArrayBuffer类型
      value: buffer,
      
      success (res) {
        // 将发送的数据打印出来
        console.log(buffer)
        console.log('writeBLECharacteristicValue success', res.errMsg)
        wx.showToast({
          title: '发送成功',
        })
      },
      fail(res){
        wx.showToast({
          title: '发送失败',
        })
      }
    })
  }
})


 

  • 25
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
当然,这是一个简单的示例代码,用于实现微信小程序蓝牙连接数据收发功能。你可以根据你的实际需进行修改和扩展。 在小程序的js文件,你可以按照以下步骤进行蓝牙连接数据收发操作: ```javascript // 引入蓝牙插件 const bluetooth = requirePlugin('bluetooth') // 初始化蓝牙适配器 bluetooth.init() // 搜索附近的蓝牙设备 bluetooth.startDiscovery({ success: function(res) { console.log('搜索成功', res.devices) // 在搜索到设备后,可以选择一个设备进行连接 connectToDevice(res.devices[0].deviceId) }, fail: function(res) { console.log('搜索失败', res.errMsg) } }) // 连接指定的蓝牙设备 function connectToDevice(deviceId) { bluetooth.createBLEConnection({ deviceId: deviceId, success: function(res) { console.log('连接成功', res) // 连接成功后,可以发送数据蓝牙设备 sendDataToDevice(deviceId, 'Hello, Bluetooth!') }, fail: function(res) { console.log('连接失败', res.errMsg) } }) } // 发送数据蓝牙设备 function sendDataToDevice(deviceId, data) { // 将符串转换为ArrayBuffer let buffer = new Uint8Array(data.length) for (let i = 0; i < data.length; i++) { buffer[i] = data.charCodeAt(i) } bluetooth.writeBLECharacteristicValue({ deviceId: deviceId, serviceId: '服务ID', characteristicId: '特征值ID', value: buffer.buffer, success: function(res) { console.log('发送成功', res) }, fail: function(res) { console.log('发送失败', res.errMsg) } }) } // 监听蓝牙设备发送过来的数据 bluetooth.onBLECharacteristicValueChange(function(res) { // 将ArrayBuffer转换为符串 let data = String.fromCharCode.apply(null, new Uint8Array(res.value)) console.log('接收到数据', data) }) ``` 在上面的代码,你需要将`服务ID`和`特征值ID`替换为你实际使用的蓝牙服务特征值的UUID。另外,这里使用了符串转换为ArrayBuffer和ArrayBuffer转换为符串的方法,你可以根据你的实际需进行调整。 希望这些详细代码能帮助到你!如果你有其他问题,请随时提问。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值