• 使用微信小程序控制蓝牙小车(微信小程序端)


    使用接口

    微信小程序官方开发文档

    接口说明
    wx.openBluetoothAdapter初始化蓝牙模块
    wx.closeBluetoothAdapter关闭蓝牙模块(调用该方法将断开所有已建立的连接并释放系统资源)
    wx.startBluetoothDevicesDiscovery开始搜寻附近的蓝牙外围设备
    wx.stopBluetoothDevicesDiscovery停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索
    wx.onBluetoothDeviceFound监听搜索到新设备的事件
    wx.createBLEConnection连接蓝牙低功耗设备
    wx.closeBLEConnection断开与蓝牙低功耗设备的连接
    wx.getBLEDeviceServices获取蓝牙低功耗设备所有服务
    wx.getBLEDeviceCharacteristics获取蓝牙低功耗设备某个服务中所有特征 (characteristic)
    wx.readBLECharacteristicValue读取蓝牙低功耗设备特征值的二进制数据
    wx.writeBLECharacteristicValue向蓝牙低功耗设备特征值中写入二进制数据
    wx.showToast显示消息提示框

    界面效果

    在这里插入图片描述
    图片素材库地址
    项目目录
    项目目录列表

    界面设计

    1. app.json中添加一个新页面"pages/home/home"
    {
      "pages":[
        "pages/home/home",
        "pages/index/index",
        "pages/logs/logs"
      ],
      "window":{
        "backgroundTextStyle":"light",
        "navigationBarBackgroundColor": "#fff",
        "navigationBarTitleText": "Weixin",
        "navigationBarTextStyle":"black"
      },
      "style": "v2",
      "sitemapLocation": "sitemap.json"
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    1. 设计界面home.wxml
    
    <button type="primary" class = "connectBLE" bindtap = "openBluetoothAdapter">连接蓝牙button>
    <button class = "disconnectBLE" bindtap = "closeBluetoothAdapter">断开蓝牙button>  
    
    <button class="custom-button" style="bottom: -395px" bindtap = "btnClickDown">
      <image class="button-image" src="/image/doubledown.png">image>
    button>
    
    <button class="custom-button" style="bottom: -15px" bindtap = "btnClickUp">
      <image class="button-image" src="/image/doubleup.png">image>
    button>
    
    <view>
      <button class="custom-button" style="bottom: -60px; left: -35%" bindtap = "btnClickLeft">
        <image class="button-image-1" src="/image/doubleleft.png">image>
      button>
    view>
    
    <view>
      <button class="custom-button" style="bottom: 40px; left: 35%" bindtap = "btnClickRight">
        <image class="button-image-1" src="/image/doubleright.png">image>
      button>
    view>
    
    <view>
      <button class="custom-button" style="bottom: 134px; left: 0%" bindtap = "btnClickStop">
        <image class="button-image-2" src="/image/remove.png">image>
      button>
    view>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    1. 画面渲染home.wxss
    /* pages/home/home.wxss */
    .connectBLE {
      width: 49% !important;
      float: left;
      font-size: 100;
    }
    
    .disconnectBLE {
      width: 49% !important;
      float: right;
      font-size: 100;
      color: red;
    }
    
    .custom-button {
      position: relative;
      width: 100px;
      height: 100px;
      border: none;
      padding: 0;
      overflow: hidden;
      background: transparent;   /*设置背景颜色一致*/
      border-color: transparent; /*设置边框颜色一致*/
    }
    
    .button-image {
      object-fit: contain;
      width: 75%;
      height: 110%;
    }
    
    .button-image-1 {
      object-fit: contain;
      width: 75%;
      height: 110%;
    }
    
    .button-image-2 {
      object-fit: contain;
      width: 60%;
      height: 100%;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    界面逻辑设计

    连接的目标蓝牙名称为ESP_SPP_SERVER

    // pages/home/home.js
    Page({
    
      /**
       * 页面的初始数据
       */
      data: {
        connected: false,
        serviceId: "",
      },
    
      //蓝牙初始化
      openBluetoothAdapter() {
        if(this.data.connected)
        {
          return
        }
        wx.openBluetoothAdapter({
          success: (res) => {
            console.log('bluetooth initialization success', res)
            this.startBluetoothDevicesDiscovery()
          },
          fail: (err) => {
            wx.showToast({
              title: '蓝牙适配器初始化失败',
              icon: 'none'
            })
            return
          }
        })
      },
      //关闭蓝牙初始化
      closeBluetoothAdapter() {
        wx.closeBluetoothAdapter({
          success: (res) => {
            console.log('bluetooth deinitialization success', res)
          },
          fail: (err) => {
            wx.showToast({
              title: '蓝牙适配器解初始化失败',
              icon: 'none'
            })
            return
          }
        })
      },
      //开始搜寻附近的蓝牙外围设备
      startBluetoothDevicesDiscovery() {
        wx.startBluetoothDevicesDiscovery({
          success: (res) => {
            console.log('startBluetoothDevicesDiscovery success', res)
            this.onBluetoothDeviceFound()
          },
          fail: (err) => {
            wx.showToast({
              title: '蓝牙适配器解初始化失败',
              icon: 'none'
            })
            return
          }
        })
      },
      //监听搜索到新设备的事件
      onBluetoothDeviceFound() {
        let found_device = false
        const timer = setTimeout(() => {
          if (!found_device) {
            console.error('未找到设备');
            wx.showToast({
              title: '未找到设备',
              icon: 'none'
            })
          }
        }, 2000); // 设置定时器为10秒
      
        wx.onBluetoothDeviceFound((res) => {
          res.devices.forEach(device => {
            if (device.name === 'ESP_SPP_SERVER') {
              console.log('find target device')
              found_device = true; // 找到目标设备,将标志变量设置为已找到
              clearTimeout(timer); // 取消定时器
              this.createBLEConnection(device.deviceId)
            }
          });
        });
      },
      //连接蓝牙低功耗设备
      createBLEConnection(deviceId) {
        wx.createBLEConnection({
          deviceId,
          success:() => {
            this.setData({
              connected: true,
            })
            console.log('connect device success')
            this.getBLEDeviceServices(deviceId)
            wx.stopBluetoothDevicesDiscovery()
          },
          fail:(err) => {
            wx.showToast({
              title: '建立蓝牙连接失败',
              icon: 'none'
            })
          }
        })
      },
      //获取蓝牙低功耗设备所有服务
      getBLEDeviceServices(deviceId) {
        wx.getBLEDeviceServices({
          deviceId,
          success:(res) => {
            for (let i = 0; i < res.services.length; i++) {
              if(res.services[i].isPrimary) {
                this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
                return
              }
            }
          },
          fail:(res) => {
            console.log('getBLEDeviceServices fail', res.errMsg)
          }
        })
      },
      //获取蓝牙低功耗设备某个服务中所有特征
      getBLEDeviceCharacteristics(deviceId, serviceId) {
        wx.getBLEDeviceCharacteristics({
          deviceId,
          serviceId,
          success: (res) => {
            for (let i = 0; i < res.characteristics.length; i++) {
              let item = res.characteristics[i]
              if(item.properties.read) {
                wx.readBLECharacteristicValue({
                  deviceId,
                  serviceId,
                  characteristicId: item.uuid,
                })
              }
              if(item.properties.write)
              {
                this._deviceId = deviceId
                this._serviceId = serviceId
                this._characteristicId = item.uuid
              }
            }
          },
          fail:(res) => {
            console.log('get characteristicId fail', res.errMsg)
          }
        })
      },
      //关闭蓝牙服务
      closeBluetoothAdapter() {
        wx.closeBLEConnection({
          deviceId: this._deviceId,
          success: (res) => {
            console.log('disconnect success')
          },
          fail: (res) => {
            console.log('disconnect fail',res.errMsg)
          }
        })
        wx.closeBluetoothAdapter({
          success: (res) => {
            console.log('close success')
          },
          fail: (res) => {
            console.log('close fail',res.errMsg)
          }
        })
        this.data.connected = false
        console.log('close connection')
      },
    
      btnClickDown() {
        this.tipsBluetoothWarn()
        this.writeBluetoothValue('down')
        console.log('click down')
      },
      btnClickUp() {
        this.tipsBluetoothWarn()
        this.writeBluetoothValue('up')
        console.log('click up')
      },
      btnClickLeft() {
        this.tipsBluetoothWarn()
        this.writeBluetoothValue('left')
        console.log('click left')
      },
      btnClickRight() {
        this.tipsBluetoothWarn()
        this.writeBluetoothValue('right')
        console.log('click right')
      },
      btnClickStop() {
        this.tipsBluetoothWarn()
        this.writeBluetoothValue('stop')
        console.log('click stop')
      },
      tipsBluetoothWarn()
      {
        if(!this.data.connected)
        {
          wx.showToast({
            title: '蓝牙未连接',
            icon: 'none'
          })
        }
      },
      writeBluetoothValue(value) {
        if(!this.data.connected)
        {
          return
        }
        const buffer = new ArrayBuffer(value.length)
        const dataView = new DataView(buffer)
        for (let i = 0; i < value.length; i++) {
          dataView.setUint8(i, value.charCodeAt(i))
        }
        wx.writeBLECharacteristicValue({
          deviceId: this._deviceId,
          serviceId: this._serviceId,
          characteristicId: this._characteristicId,
          value: buffer,
          success (res) {
            console.log('writeBLECharacteristicValue success', res.errMsg)
          },
          fail (res) {
            console.log('writeBLECharacteristicValue fail', res.errMsg, res.errCode)
          }
        })
      },
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad(options) {
    
      },
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239

    20231113 优化改成按下车动,松开车停

    1. 修改文件home.wxml
    
    <button type="primary" class = "connectBLE" bindtap = "openBluetoothAdapter">连接蓝牙button>
    <button class = "disconnectBLE" bindtap = "closeBluetoothAdapter">断开蓝牙button>  
    
    <button class="custom-button" style="bottom: -395px" bindtouchstart = "btnClickDown" bindtouchend = "btnClickStop">
      <image class="button-image" src="/image/doubledown.png">image>
    button>
    
    <button class="custom-button" style="bottom: -15px" bindtouchstart = "btnClickUp" bindtouchend = "btnClickStop">
      <image class="button-image" src="/image/doubleup.png">image>
    button>
    
    <view>
      <button class="custom-button" style="bottom: -60px; left: -35%" bindtouchstart = "btnClickLeft" bindtouchend = "btnClickStop">
        <image class="button-image-1" src="/image/doubleleft.png">image>
      button>
    view>
    
    <view>
      <button class="custom-button" style="bottom: 40px; left: 35%" bindtouchstart = "btnClickRight" bindtouchend = "btnClickStop">
        <image class="button-image-1" src="/image/doubleright.png">image>
      button>
    view>
    
    <view>
      <button class="custom-button" style="bottom: 134px; left: 0%" bindtap = "btnClickStop">
        <image class="button-image-2" src="/image/remove.png">image>
      button>
    view>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
  • 相关阅读:
    【华为机试真题 JAVA】火星文计算-100
    CAD文件转奥维 转shapefile
    【Java开发岗:SpringCould篇】
    浅谈Router和Route
    [笔记] 十进制转n进制
    [vue]——vue3.0+高德地图的正确打开方式
    [Spring Framework]DI依赖注入②(自动装配、集合注入)
    计算机网络 套接字函数 | socket、bind、listen、accept、connect
    6.1 线性空间
    Web3:数字化社会的下一步
  • 原文地址:https://blog.csdn.net/qq_44708426/article/details/134333465