小程序代码
index.wxml

<button bindtap="click">扫码</button>

index.js

Page({
  data: {
    deviceName: "",
  },

  /* 点击事件 */
  click: function (event) {
    var that = this;
    //调用扫码功能
    wx.scanCode({
      success: (res) => {
        console.log(res)
        that.setData({
          deviceName: res.result
        })
        //获取到二维码中的蓝牙设备名后跳转到连接页面
        var title = that.data.deviceName;
        wx.redirectTo({
          url: '../detail/detail?id=' + title
        })
      },
      fail: (res) => {
        wx.showToast({
          title: '扫码失败',
          icon: 'success',
          duration: 2000
        })
      },
    })
  },
})

detail.wxml

<view class="page" xmlns:wx="http://www.w3.org/1999/xhtml">
    <view class="page__bd">
        <view class="weui-cells__title_big">蓝牙与Arduion通信测试</view>
        <view class="weui-cells__title">发送数据</view>
        <view class="weui-cell  weui-cell_vcode">
            <view class="weui-cell__hd">
                <view class="weui-label">code</view>
            </view>
            <view class="weui-cell__bd">
                <input type="number" bindinput="bindKeyInput" class="weui-input" placeholder="待发送的数据" />
            </view>
            <view class="weui-cell__ft">
                <view class="weui-vcode-btn" bindtap="SendTap">发送</view>
            </view>
        </view>
        <view class="weui-cells__title">接收数据</view>
        <view class="weui-cell  weui-cell_vcode">
            <view class="section">
                <textarea disabled class="receive_area" value="{{ReceiveNum}}" />
                </view>
        </view>
    </view>
</view>

detail.js

 Page({
  data: {
    deviceId: '',
    codeNum: '00',
    ReceiveNum: '',
  },
  //获取二维码中的蓝牙name,然后连接
  onLoad: function (options) {
    wx.showLoading({
      title: '请打开蓝牙',
    });
    console.log(options);
    this.setData({
      deviceName: options.id,
    });
    console.log('设备的Name', this.data.deviceName);
    var that = this;
    var deviceName = options.id;
    wx.closeBluetoothAdapter({
      success: function (res) {
        console.log('关闭蓝牙模块');
        /* 初始化蓝牙适配器 */
        wx.openBluetoothAdapter({
          success: function (res) {
            console.log('初始化蓝牙适配器成功');
            wx.hideLoading();
            wx.showLoading({
              title: '请稍后....',
            });
            wx.startBluetoothDevicesDiscovery({
              allowDuplicatesKey: false,
              success: function (res) {
                console.log('这里是开始搜索附近设备', res);
                //添加延迟
                setTimeout(() => {
                  wx.getBluetoothDevices({
                    success: function (res) {
                      console.log(res)
                      //在搜索到的所有蓝牙中找到需要连接的那一个蓝牙
                      for (var i = 0; i < res.devices.length; i++) {
                        if (res.devices[i].name == deviceName) {
                          that.setData({
                            deviceId: res.devices[i].deviceId,
                          })
                          console.log(res.devices[i].deviceId)
                          wx.hideLoading();
                          /* 连接中动画 */
                          wx.showLoading({
                            title: '正在连接...',
                          });
                          that.CreateBLEConnection();
                        }
                      }
                    },
                    fail: function () {
                      console.log("搜索蓝牙设备失败")
                    }
                  });
                }, 1300);
              },
            });
          },
        })
      }
    });
  },



  /**
   * 连接蓝牙
   */
  CreateBLEConnection: function () {
    var that = this;
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log('停止搜索设备', res)
      }
    })
    /* 开始连接蓝牙设备 */
    wx.createBLEConnection({
      deviceId: that.data.deviceId,
      success: function (res) {
        console.log('连接成功', res);
        wx.hideLoading();
        /* 获取设备的服务UUID */
        wx.getBLEDeviceServices({
          deviceId: that.data.deviceId,
          success: function (service) {
            var all_UUID = service.services; //取出所有的服务
            console.log('所有的服务', all_UUID);
            var UUID_lenght = all_UUID.length; //获取到服务数组的长度
            /* 遍历服务数组 */
            for (var index = 0; index < UUID_lenght; index++) {
              var ergodic_UUID = all_UUID[index].uuid; //取出服务里面的UUID
              var UUID_slice = ergodic_UUID.slice(4, 8); //截取4到8位
              /* 判断是否是我们需要的FFE0 */
              if (UUID_slice == 'FFE0' || UUID_slice == 'ffe0') {
                var index_uuid = index;
                that.setData({
                  serviceId: all_UUID[index_uuid].uuid //确定需要的服务UUID
                });
              };
            };
            console.log('需要的服务UUID', that.data.serviceId)
            that.Characteristics(); //调用获取特征值函数
          },
        });
      },
    })
  },


  /**
   * 调用获取特征值函数
   */
  Characteristics: function () {
    var that = this;
    var device_characteristics = [];
    var characteristics_uuid = {};
    wx.getBLEDeviceCharacteristics({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      success: function (res) {
        var characteristics = res.characteristics; //获取到所有特征值
        var characteristics_length = characteristics.length; //获取到特征值数组的长度
        console.log('获取到特征值', characteristics);
        console.log('获取到特征值数组长度', characteristics_length);

        /* 遍历获取characteristicsId */
        for (var index = 0; index < characteristics_length; index++) {
          var characteristics_UUID = characteristics[index].uuid; //取出特征值里面的UUID
          var characteristics_slice = characteristics_UUID.slice(4, 8); //截取4到8位
          /* 判断是否是我们需要的FFE1 */
          if (characteristics_slice == 'FFE1' || characteristics_slice == 'ffe1') {
            var index_uuid = index;
            that.setData({
              characteristicsId: characteristics[index_uuid].uuid //确定的写入UUID
            });
          };
        };
        console.log('写入characteristicsId', that.data.characteristicsId);
        /* 监听接收数据 */
        that.ReceiveTap();
      },
    })
  },



  /**
   * 发送指令
   */
  SendTap: function () {
    var that = this;
    var value_ascii = "";
    var value_initial = that.data.codeNum; //发送的信息
    console.log('输入框中的值', value_initial);
    /* 以Ascii字符发送 */
    var value_split = value_initial.split(''); //将字符一个一个分开
    console.log('value_split', value_split);
    for (var i = 0; i < value_split.length; i++) {
      value_ascii = value_ascii + value_split[i].charCodeAt().toString(16); //转为Ascii字符后连接起
    }
    var value = value_ascii;
    console.log('转为Ascii码值', value);
    var write_function = that.write(value); //调用数据发送函数
  },


  /**
   * 接收指令
   */
  ReceiveTap: function () {
    var that = this;
    wx.notifyBLECharacteristicValueChange({
      state: true,
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.characteristicsId,
      success: function (res) {
        console.log('notifyBLECharacteristicValueChange success', res.errMsg)
      }
    })
    function ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('');
    }
    wx.onBLECharacteristicValueChange(function (res) {
      var receive_num = that.hexCharCodeToStr(ab2hex(res.value));
      that.setData({
        ReceiveNum: "收到的返回码为: "+receive_num
      })
      console.log('收到的数据为:', receive_num)
    })
  },

  /**
   * 16进制ascii转字符
   */
  hexCharCodeToStr: function (hexCharCodeStr) {
    var trimedStr = hexCharCodeStr.trim();
    var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
    var len = rawStr.length;
    if (len % 2 !== 0) {
      console.log("存在非法字符!");
      return "";
    }
    var curCharCode;
    var resultStr = [];
    for (var i = 0; i < len; i = i + 2) {
      curCharCode = parseInt(rawStr.substr(i, 2), 16);
      resultStr.push(String.fromCharCode(curCharCode));
    }
    return resultStr.join("");
  },

  /**
   * 数据发送函数
   * @param {*} str 
   */
  write: function (str) {
    var that = this;
    var value = str;
    console.log('value', value);
    /* 将数值转为ArrayBuffer类型数据 */
    var typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }));
    var buffer = typedArray.buffer;
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.characteristicsId,
      value: buffer,
      success: function (res) {
        console.log('数据发送成功', res);
        wx.showToast({
          title: '发送成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (res) {
        console.log('调用失败', res);
        /* 调用失败时,再次调用 */
        wx.writeBLECharacteristicValue({
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.characteristicsId,
          value: buffer,
          success: function (res) {
            console.log('第2次数据发送成功', res);
            wx.showToast({
              title: '发送成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function (res) {
            console.log('第2次调用失败', res);
            /* 调用失败时,再次调用 */
            wx.writeBLECharacteristicValue({
              deviceId: that.data.deviceId,
              serviceId: that.data.serviceId,
              characteristicId: that.data.characteristicsId,
              value: buffer,
              success: function (res) {
                console.log('第3次数据发送成功', res);
                wx.showToast({
                  title: '发送成功',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: function (res) {
                console.log('第3次调用失败', res);
              }
            });
          }
        });
      }
    });
  },


  /**
   * 同步input数据到data
   */
  bindKeyInput: function (e) {
    this.setData({
      codeNum: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    wx.closeBLEConnection({
      deviceId: that.data.deviceId,
      success: function (res) {
        console.log('断开设备连接', res);
      }
    });
  },
})

arduino代码

String comdata = "";
int SW = 8;
void setup()
{
  Serial.begin(9600);
  pinMode(SW, OUTPUT);
}

void loop()
{
  while (Serial.available() > 0) {
    comdata += char(Serial.read());  //每次读一个char字符,并相加
    delay(2);
  }

  if (comdata.length() > 0) {
    Serial.println(comdata); //打印接收到的字符
    if (comdata == "01") {
      digitalWrite(SW, HIGH);   //开锁信号
      delay(500);               // wait for a second
      digitalWrite(SW, LOW);    // turn the LED off by making the voltage LOW
      Serial.print("02");    
    }
    comdata = "";
  }

}

点击视频演示

标签: HC06蓝牙, arduino, 无线控制

添加新评论