ESP32 小程序与蓝牙通信/蓝牙配网/低功率蓝牙通信/Bluetooth

须知

很喜欢 ESP32,便宜的结果就是性能差了点,一旦你使用蓝牙服务你可怜的内存会被无情的占用,如果需要配网首选还是wifi的好。

准备

首先你需要ESP32开发板的库
https://github.com/espressif/arduino-esp32
这个库直接COPY到arduino\hardware 中即可,注意目录结构
运气好的话你可以直接使用了,我用的开发板是ESP32 WROVER MODULE 如果你的库没问题了,你可以在开发板管理中找到它。

代码

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID        ""   //你可以通过上面的网址去生成UUID
#define CHARACTERISTIC_UUID ""

//由终端发来的信息将在这里显示
class MyCallbacks: public BLECharacteristicCallbacks {
  void onWrite(BLECharacteristic *pCharacteristic) {
    std::string value = pCharacteristic->getValue();
    if (value.length() > 0) {
        for (int i = 0; i < value.length(); i++)
          Serial.print(value[i]);
          Serial.println();
    }
  }
};

void setup() {
  Serial.begin(9600);

  BLEDevice::init("JDY-16"); //当服务启动时,你将在你的手机蓝牙中发现它
  BLEServer *pServer = BLEDevice::createServer();

  BLEService *pService = pServer->createService(SERVICE_UUID);

  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID,
                                         BLECharacteristic::PROPERTY_READ |
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setCallbacks(new MyCallbacks());

  pCharacteristic->setValue("Hello World");
  pService->start();

  BLEAdvertising *pAdvertising = pServer->getAdvertising();
  pAdvertising->start();
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);

没错就这几行代码,蓝牙服务就开启了。如果你觉得它耗内存太大,你可以参考我的另一篇文章,里面有wifi配网的方法。

小程序代码

connectBle:function(){
    console.log(this.data.accountInput+"  "+this.data.pswInput);
    let _this=this;
    if (wx.openBluetoothAdapter) {
            wx.openBluetoothAdapter({
                success: function(res) {
                    /* 获取本机的蓝牙状态 */
                    setTimeout(() => {
                        _this.getBluetoothAdapterState()
                    }, 1000)
                    console.log(res)
                },
                fail: function(err) {
                  // 初始化失败
                  console.log("err"+err);
                  console.log(JSON.stringify(err));
                }
            })
        } else {
            console.log("step0");
        }
  },
  getBluetoothAdapterState() {
    let _this=this;
    wx.getBluetoothAdapterState({
        success: function(res) {
          console.log(res)
          _this.startBluetoothDevicesDiscovery();
        },
        fail(res) {
            console.log(res);
        }
    })
  },
  startBluetoothDevicesDiscovery() {
    var _this = this;
        wx.startBluetoothDevicesDiscovery({
            success: function(res) {
                /* 获取蓝牙设备列表 */
                console.log(res);
                _this.getBluetoothDevices();
            },
            fail(err) {
              console.log(err);
            }
        })
  },
  /**
  * JDY-16 为设备名称
  */
  getBluetoothDevices() {
    var that = this;
        wx.getBluetoothDevices({
            services: [],
            allowDuplicatesKey: false,
            interval: 0,
            success: function(res) {
              console.log(res);
                if (res.devices.length > 0) {
                  console.log(res.devices.length);
                  for (let i = 0; i < res.devices.length; i++) {
                    console.log(res.devices[i].name)
                            if ("JDY-16" == res.devices[i].name) {//这个是你在adruino 代码中设置的蓝牙设备名称
                                /* 根据指定的蓝牙设备名称匹配到deviceId */
                                console.log(res.devices[i].name)
                                that.connectTO(res.devices[i].deviceId);
                                that.setData({
                                  deviceId:res.devices[i].deviceId
                                });
                            };
                        };
                } else {
                }
            },
            fail(err) {
                console.log(err, '获取蓝牙设备列表失败=====')
            }
        })
  },
  connectTO(deviceid) {
    console.log("connect....");
    console.log(deviceid);
    let that=this;
      wx.createBLEConnection({
          deviceId: deviceid,
          success: function(res) {
              console.log(res);
              /* 4.获取连接设备的service服务 */
              console.log("连接完成..");

              wx.stopBluetoothDevicesDiscovery({
                  success: function(res) {
                      console.log(res, '停止搜索')
                  },
                  fail(err) {
                    console.log(err);
                  }
              })
          },
          fail: function(res) {
          }
      })
  },
  getMsg(){
    console.log(this.data.accountInput);
    console.log(this.data.pswInput);
    //表单验证重要
    //发送的消息  id:xxxxxxxxxxx
    //           pw:xxxxxxxxxx
    //每次发送信息不得超过20个字节,在表单验证中限制 除去包头3个字节,wifi账号或密码不得超过17个字节
    this.sendMsg("id:"+this.data.accountInput);
    //你不能一口气把消息发送完成,只能分批发送,那么你需要延迟,否则会被认为是一条信息,那么超出的部分会被截断
    setTimeout(() => {
       this.sendMsg("pw:"+this.data.pswInput);
    }, 1000);
  },
  sendMsg(str) {

    let that = this;
    let dataBuffer = new ArrayBuffer(str.length);
    let dataView = new DataView(dataBuffer)
    for (var i = 0; i < str.length; i++) {
        dataView.setUint8(i, str.charAt(i).charCodeAt())
    }
    let dataHex = that.ab2hex(dataBuffer);
    this.writeDatas = that.hexCharCodeToStr(dataHex);
    wx.writeBLECharacteristicValue({
        deviceId: that.data.deviceId,
        serviceId: "",
        characteristicId:"", //这两个ID请自己生成
        value: dataBuffer,
        success: function (res) {
            console.log(res);
        },
        fail: function (err) {
          console.log(err);
        },
        complete: function (res) {
        }
    })
  },
 /*转成二进制*/
  ab2hex (buffer) {
    var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer), function (bit) {
    return ('00' + bit.toString(16)).slice(-2)
    })
    return hexArr.join('')
  },
  accountInput:function(e){
    this.setData({
      accountInput:e.detail.value
    }) 
  },
 /*转成可展会的文字*/
  hexCharCodeToStr(hexCharCodeStr) {
    var trimedStr = hexCharCodeStr.trim();
    var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
    var len = rawStr.length;
    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('');
  },

在这里插入图片描述
在这里插入图片描述

  • 4
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值