微信小程序通过蓝牙连接ESP32控制LED灯

这篇具有很好参考价值的文章主要介绍了微信小程序通过蓝牙连接ESP32控制LED灯。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本文主要基于网上已有的代码以及官方给定示例代码进行修改。如有不妥请指出,谢谢啦。

一、思路分析

1.1 整体思路

据我了解,微信小程序只能通过低功耗蓝牙(BLE)进行控制。
蓝牙小程序调用灯按钮地代码,Arduino,ESP32,微信小程序,微信小程序,小程序,物联网

1.2 微信小程序思路

蓝牙小程序调用灯按钮地代码,Arduino,ESP32,微信小程序,微信小程序,小程序,物联网

1.3 ESP32端思路

BLE蓝牙部分设置流程(通过该程序就能让esp32广播蓝牙,同时手机也可搜索到蓝牙设备):
蓝牙小程序调用灯按钮地代码,Arduino,ESP32,微信小程序,微信小程序,小程序,物联网

//
获取蓝牙接收的数据与处理(主要用到 if 语句,用于判断接收的数据是控制LED灯开还是LED灯关):
蓝牙小程序调用灯按钮地代码,Arduino,ESP32,微信小程序,微信小程序,小程序,物联网

二、 控制代码

2.1 微信小程序端代码

全局变量

App({
  onLaunch() {
    // 展示本地存储能力
    
  },
  globalData: {
    appdid : null,
    appsid : null,
    appcid : null
  }
})

蓝牙搜索与连接界面

<wxs module="utils">
module.exports.max = function(n1, n2) {
  return Math.max(n1, n2)
}
module.exports.len = function(arr) {
  arr = arr || []
  return arr.length
}
</wxs>
<button bindtap="openBluetoothAdapter">开始扫描</button>
<button bindtap="stopBluetoothDevicesDiscovery">停止扫描</button>
<button bindtap="closeBluetoothAdapter">结束流程</button>

<view class="devices_summary">已发现 {{devices.length}} 个外围设备:</view>
<scroll-view class="device_list" scroll-y scroll-with-animation>
  <view wx:for="{{devices}}" wx:key="index"
   data-device-id="{{item.deviceId}}"
   data-name="{{item.name || item.localName}}"
   bindtap="createBLEConnection" 
   class="device_item"
   hover-class="device_item_hover">
    <view style="font-size: 16px; color: #333;">{{item.name}}</view>
    <view style="font-size: 10px">信号强度: {{item.RSSI}}dBm ({{utils.max(0, item.RSSI + 100)}}%)</view>
    <view style="font-size: 10px">UUID: {{item.deviceId}}</view>
    <view style="font-size: 10px">Service数量: {{utils.len(item.advertisServiceUUIDs)}}</view>
  </view>
</scroll-view>

<view class="connected_info" wx:if="{{connected}}">
  <view>
    <text>已连接到 {{name}}</text>
    <view class="operation">
    <button wx:if="{{canWrite}}" size="mini" bindtap="writeBLECharacteristicValue">写数据</button>
    <button size="mini" bindtap="closeBLEConnection">断开连接</button>
    </view>
  </view>
  <view wx:for="{{chs}}" wx:key="index" style="font-size: 12px; margin-top: 10px;">
    <view>特性UUID: {{item.uuid}}</view>
    <view>特性值: {{item.value}}</view>
  </view>
</view>


//index.js
var app = getApp()

function dsc(ddID,ssID,ccID){
  app.globalData.appdid = ddID
  app.globalData.appsid = ssID
  app.globalData.appcid = ccID
  console.log("kai关灯"+app.globalData.appcid)
}

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

Page({
  data: {
    devices: [],
    connected: false,
    chs: [],
  },
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    wx.navigateTo({
      url:'/pages/conpage/conpage',
      success: (res) => {
        console.log('跳转')
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  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
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        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.setData({
              canWrite: true
            })
            dsc(deviceId,serviceId,item.uuid)
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            //this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听,保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },
/*
  ledon: function(e){
    console.log("开灯")
    this.writeBLECharacteristicValue(0x61)
    },
    
  ledoff: function(e){
    console.log("关灯")
    this.writeBLECharacteristicValue(0x62)
  },

  writeBLECharacteristicValue(leddata) {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, leddata)
    wx.writeBLECharacteristicValue({
      deviceId: appdid,
      serviceId: appsid,
      characteristicId: appcid,
      value: buffer,
    })
  },
*/
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  }
})

LED灯开关控制界面

<!--pages/conpage/conpage.wxml-->
<text>LED控制界面</text>
<button bindtap="ledon">开灯</button>
<button bindtap="ledoff">关灯</button>
// pages/conpage/conpage.js
var app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {

  },

  ledon: function(e){
    console.log("开灯")
    this.writeBLECharacteristicValue(0x61)
    },
    
  ledoff: function(e){
    console.log("关灯")
    this.writeBLECharacteristicValue(0x62)
  },

  writeBLECharacteristicValue(leddata) {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, leddata)
    wx.writeBLECharacteristicValue({
      deviceId: app.globalData.appdid,
      serviceId: app.globalData.appsid,
      characteristicId: app.globalData.appcid,
      value: buffer,
    })
  }  
})

2.2 ESP32端代码(基于Arduino)

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

#define Led 2

uint8_t txValue = 0;                         //后面需要发送的值
BLEServer *pServer = NULL;                   //BLEServer指针 pServer
BLECharacteristic *pTxCharacteristic = NULL; //BLECharacteristic指针 pTxCharacteristic
bool deviceConnected = false;                //本次连接状态
bool oldDeviceConnected = false;             //上次连接状态d
// See the following for generating UUIDs: https://www.uuidgenerator.net/
#define SERVICE_UUID "12a59900-17cc-11ec-9621-0242ac130002" // UART service UUID
#define CHARACTERISTIC_UUID_RX "12a59e0a-17cc-11ec-9621-0242ac130002"
#define CHARACTERISTIC_UUID_TX "12a5a148-17cc-11ec-9621-0242ac130002"
 
class MyServerCallbacks : public BLEServerCallbacks
{
    void onConnect(BLEServer *pServer)
    {
        deviceConnected = true;
    };
 
    void onDisconnect(BLEServer *pServer)
    {
        deviceConnected = false;
    }
};
 
class MyCallbacks : public BLECharacteristicCallbacks
{
    void onWrite(BLECharacteristic *pCharacteristic)
    {
        std::string rxValue = pCharacteristic->getValue(); //接收信息
 
        if (rxValue.length() > 0)
        { //向串口输出收到的值
            Serial.print("RX: ");
            for (int i = 0; i < rxValue.length(); i++)
                Serial.print(rxValue[i]);
            Serial.println();
            if (rxValue[0]=='a')
              digitalWrite(Led, HIGH);
            else
              digitalWrite(Led, LOW);              
        }
    }
};
 
void setup()
{
    Serial.begin(115200);
 
    // 创建一个 BLE 设备
    BLEDevice::init("ESP32BLE");//在这里面是ble的名称
 
    // 创建一个 BLE 服务
    pServer = BLEDevice::createServer();
    pServer->setCallbacks(new MyServerCallbacks()); //设置回调
    BLEService *pService = pServer->createService(SERVICE_UUID);
 
    // 创建一个 BLE 特征
    pTxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY);
    pTxCharacteristic->addDescriptor(new BLE2902());
    BLECharacteristic *pRxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
    pRxCharacteristic->setCallbacks(new MyCallbacks()); //设置回调
 
    pService->start();                  // 开始服务
    pServer->getAdvertising()->start(); // 开始广播
    Serial.println(" 等待一个客户端连接,且发送通知... ");
    pinMode(Led, OUTPUT);
}
 
void loop()
{
    // deviceConnected 已连接
    if (deviceConnected)
    {
        pTxCharacteristic->setValue(&txValue, 1); // 设置要发送的值为1
        pTxCharacteristic->notify();              // 广播
        txValue++;                                // 指针数值自加1
        delay(2000);                              // 如果有太多包要发送,蓝牙会堵塞
    }
 
    // disconnecting  断开连接
    if (!deviceConnected && oldDeviceConnected)
    {
        delay(500);                  // 留时间给蓝牙缓冲
        pServer->startAdvertising(); // 重新广播
        Serial.println(" 开始广播 ");
        oldDeviceConnected = deviceConnected;
    }
 
    // connecting  正在连接
    if (deviceConnected && !oldDeviceConnected)
    {
        // do stuff here on connecting
        oldDeviceConnected = deviceConnected;
    }
}

测试结果

小程序初始界面
蓝牙小程序调用灯按钮地代码,Arduino,ESP32,微信小程序,微信小程序,小程序,物联网
点击开始扫描之后,获取到周围的蓝牙设备
蓝牙小程序调用灯按钮地代码,Arduino,ESP32,微信小程序,微信小程序,小程序,物联网
点击所对应的设备之后,就会跳转到灯的控制界面。在此界面可以控制开灯或者关灯
蓝牙小程序调用灯按钮地代码,Arduino,ESP32,微信小程序,微信小程序,小程序,物联网
开灯的结果图:
蓝牙小程序调用灯按钮地代码,Arduino,ESP32,微信小程序,微信小程序,小程序,物联网
关灯的结果图
蓝牙小程序调用灯按钮地代码,Arduino,ESP32,微信小程序,微信小程序,小程序,物联网

展望

能够通过蓝牙控制灯的亮灭,于是我们可以拓展出更多的功能,比如遥控车,实现遥控车前进后退,左转右转等等。

参考资料

esp32蓝牙
微信小程序低功耗蓝牙官方文档文章来源地址https://www.toymoban.com/news/detail-766875.html

到了这里,关于微信小程序通过蓝牙连接ESP32控制LED灯的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 阿里云iot haas Micropython连接esp32;esp32物联网设备上报信息及云端信息获取;远程控制设备自带led熄灭;网页界面交互远程控制

    参考:https://blog.csdn.net/HaaSTech/article/details/125975052 https://iot.console.aliyun.com/ https://www.bbsmax.com/A/x9J2X8nZd6/ 首先烧录阿里云iot haas固件: https://haas.iot.aliyun.com/haasapi/index.html#/Python/docs/zh-CN/startup/ESP32_startup ***直接下载后可以通过vscode插件烧录;烧录好后也可以在thony编辑运行代码

    2024年02月02日
    浏览(39)
  • 微信小程序蓝牙连接 uniApp蓝牙连接设备

     蓝牙列表期待效果  代码  js里面注意getBLEDeviceCharacteristics获取特征值的时候,极个别设备参数write,read,notify是乱来的,需要自己打单独处理,通过对应write,read,notify 为true的时候拿到对应的uuid,

    2024年02月04日
    浏览(49)
  • 微信小程序 - 蓝牙连接

    官网 蓝牙 (Bluetooth) | 微信开放文档        蓝牙低功耗是从蓝牙 4.0 起支持的协议,与经典蓝牙相比,功耗极低、传输速度更快,但传输数据量较小。常用在对续航要求较高且只需小数据量传输的各种智能电子产品中,比如智能穿戴设备、智能家电、传感器等,应用场景

    2024年02月05日
    浏览(45)
  • 【OneNET】_01_使用微信小程序通过新版OneNET平台获取STM32设备信息并进行控制

    笔者在这先简单介绍一下自己的整个系统,以好让各位朋友能够快速了解这篇文章对自己是否有帮助。 通过MQTT协议(笔者是直接给ESP01S刷了MQTT的AT固件,这种方法简单方便)将采集到的光照、设备电量和开锁信息上传到OneNET平台(这个过程就是向云平台你所创建设备发布主

    2024年04月24日
    浏览(138)
  • 使用微信小程序控制蓝牙小车(微信小程序端)

    微信小程序官方开发文档 接口 说明 wx.openBluetoothAdapter 初始化蓝牙模块 wx.closeBluetoothAdapter 关闭蓝牙模块(调用该方法将断开所有已建立的连接并释放系统资源) wx.startBluetoothDevicesDiscovery 开始搜寻附近的蓝牙外围设备 wx.stopBluetoothDevicesDiscovery 停止搜寻附近的蓝牙外围设备。若已

    2024年02月05日
    浏览(37)
  • 电脑蓝牙与ESP32蓝牙连接,让电脑发现ESP32

    win11蓝牙默认只查看常见蓝牙设备。ESP32创建的蓝牙很有可能是看不到的。 再蓝牙设备发现一栏选择高级,才能查看所有蓝牙设备。 只要下面几行代码,就能让PC发现ESP32 创建 BLE 服务器代码流程 1,创建一个BLE服务器。在这种情况下,ESP32充当BLE服务器。 2,创建BLE服务。 3,

    2024年02月08日
    浏览(32)
  • 微信小程序连接蓝牙设备并传递数据

    流程图 分步详解 wx.getSystemInfo(Object object)  获取系统信息 获取操作系统及版本 页面加载的时候(或者app.js中 ) ↓ 初始化蓝牙模块  wx.openBluetoothAdapter(Object object) 在用户蓝牙开关未开启或者手机不支持蓝牙功能的情况下,通过错误码(errCode=10001),提示打开蓝牙或蓝牙功能

    2024年02月08日
    浏览(42)
  • C51---蓝牙模块---连接软件---控制LED灯

    1.器件:C51、HC-08蓝牙模块、Ty-C数据线、杜邦线 2.软件:HC蓝牙助手 3.接线:VCC-VCC、GND-GND、RXD-TXD、TXD-RXD 4.烧写:STC-ISP串口助手 5.代码: #include \\\"reg52.h\\\" #include \\\"intrins.h\\\" sfr   AUXR = 0x8E; sbit  D5 = P3^7; void UartInit(void)        //9600bps@11.0592MHz {     //PCON = 0x7F;        //波特率不

    2024年02月09日
    浏览(33)
  • 微信小程序——实现蓝牙设备搜索及连接功能

    ✅作者简介:2022年 博客新星 第八 。热爱国学的Java后端开发者,修心和技术同步精进。 🍎个人主页:Java Fans的博客 🍊个人信条:不迁怒,不贰过。小知识,大智慧。 💞当前专栏:微信小程序学习分享 ✨特色专栏:国学周更-心性养成之路 🥭本文内容:微信小程序——实

    2024年02月08日
    浏览(37)
  • 微信小程序之蓝牙连接全过程封装

    1、初始化蓝牙 不管是ios操作系统还是安卓操作系统,第一步都需要初始化蓝牙 2、获取蓝牙适配器状态 3、ios和安卓的操作系统对蓝牙的连接方式不同 安卓是直接对设备的macAddress进行连接 ios需要对周边的蓝牙设备就行搜索: 4、蓝牙连接 5、获取蓝牙多个service 6、开启notif

    2024年02月15日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包