C# windows与ESP32 BLE蓝牙通讯

    在尝试使用c# 进行BLE蓝牙通讯时,由于我个人技术十分垃圾, 综合网上几个大佬的帖子,cv后,在实际使用中遇到种种问题,最后成功。此贴仅为了同样小白的玩家,参考。

本人使用的是笔记本电脑,通过硬件查询确认支持BLE通讯。

然后参考网上其他老师的帖子,几个老师都提供了一个BleCore的类,但cv过来发现存在各种引用问题,整个痛苦的过程,就不描述了,综合网上其他资料直接上结果。

首先需要引用下面这三个文件:

 参考:

未能添加对Windows.Devices.Bluetooth.dll的引用。请确保此文件可访问并且是一个有效的程序集或COM组件_windows.devices dll_vivi_and_qiao的博客-CSDN博客

 ​​​​​​百度网盘 提取码:m7ty

在项目中添加引用,在预览中将下载到的文件加入进去,然后引用

之后参考Jerrt-J老师的帖子cv了老师的类和引用

C# BLE蓝牙开发之使用Windows.Devices.Bluetooth获取小米体重秤的体重_Jerrt-J的博客-CSDN博客

代码都是cv老师的,但老师没有提供BleCore类上的引用,下面补充:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Test;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.UI.Text;

 按照老师的说法,我们要在DeviceWatcherChanged方法中,修改蓝牙的名字或者地址来进行连接,之后根据UUID获取服务。

直接执行老师的代码,选择想要连接的蓝牙名字或者地址,把名字或地址卸载老师留好的位置上,就能获得服务的UUID。

例如:if (currentDevice.Name.Equals(ESP32 BLE) || currentDevice.DeviceId.Contains("a0:b7:65:dc:0e:c6"))

通过名字或地址都可以连接成功,会获得服务的UUID如下图:

6e400003是写入,6e400002是广播,因此我们要使用两次setoperon方法来获取服务。

        /// <summary>
        /// 搜索并连接
        /// </summary>
        /// <param name="currentDevice"></param>
        private static void DeviceWatcherChanged(BluetoothLEDevice currentDevice)
        {
            byte[] _Bytes1 = BitConverter.GetBytes(currentDevice.BluetoothAddress);
            Array.Reverse(_Bytes1);
            string address = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
            Console.WriteLine("发现设备:<" + currentDevice.Name + ">  address:<" + address + ">");
            //if (currentDevice.Name.Equals(name) || currentDevice.DeviceId.Contains("a0:b7:65:dc:0e:c6"))
            if (currentDevice.Name.Equals(name))
            {
                ConnectDevice(currentDevice);
                GattCharacteristic gattCharacteristic = characteristics.Find((x) => { return x.Uuid.Equals(new Guid("6e400002-b5a3-f393-e0a9-e50e24dcca9e")); });
                bleCore.SetOpteron(gattCharacteristic);
                gattCharacteristic = characteristics.Find((x) => { return x.Uuid.Equals(new Guid("6e400003-b5a3-f393-e0a9-e50e24dcca9e")); });
                bleCore.SetOpteron(gattCharacteristic);
                Console.WriteLine("连接成功");
            }

            //指定一个对象,使用下面方法去连接设备
            //ConnectDevice(currentDevice);
        }

再次执行代码,会发现程序可以给ESP32发送信息,但是ESP32发送的信息我们无法收到,原因是老师源代码可能使用的服务是write|Notify,我实际使用需要将这两个服务分开,因此单独跳入Notify的if判断中时,没有注册接事件。所以,根据需要我将代码进行了修改,将老师下面的代码复制了一份放在上面。

if (gattCharacteristic.CharacteristicProperties == GattCharacteristicProperties.Notify)
            {
                this.CurrentNotifyCharacteristic = gattCharacteristic;
                
                this.CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;
                this.CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
                this.CurrentDevice.ConnectionStatusChanged += this.CurrentDevice_ConnectionStatusChanged;
                this.EnableNotifications(CurrentNotifyCharacteristic);
            }

再次执行,程序可以发送也可以接收。

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
ESP32和Arduino之间的蓝牙通信可以通过使用ESP32作为蓝牙服务器和Arduino作为蓝牙客户端来实现。以下是一个简单的例子,演示了如何在ESP32和Arduino之间进行蓝牙通信: 1. 首先,需要在ESP32上启用蓝牙服务器功能。可以使用Arduino IDE和ESP32BLE库来实现。以下是一个简单的代码片段,演示了如何在ESP32上启用蓝牙服务器功能: ```c++ #include <BLEDevice.h> #include <BLEServer.h> #include <BLEUtils.h> #include <BLE2902.h> BLEServer* pServer = NULL; BLECharacteristic* pCharacteristic = NULL; bool deviceConnected = false; bool oldDeviceConnected = false; uint8_t txValue = 0; #define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" #define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" class MyServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) { deviceConnected = true; }; void onDisconnect(BLEServer* pServer) { deviceConnected = false; } }; void setup() { Serial.begin(115200); BLEDevice::init("ESP32_BLE_Server"); pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); BLEService *pService = pServer->createService(SERVICE_UUID); pCharacteristic = pService->createCharacteristic( CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY | BLECharacteristic::PROPERTY_INDICATE ); pCharacteristic->addDescriptor(new BLE2902()); pService->start(); BLEAdvertising *pAdvertising = pServer->getAdvertising(); pAdvertising->addServiceUUID(pService->getUUID()); pAdvertising->setScanResponse(true); pAdvertising->setMinPreferred(0x06); pAdvertising->setMinPreferred(0x12); BLEDevice::startAdvertising(); Serial.println("Waiting for a client connection to notify..."); } void loop() { if (deviceConnected) { pCharacteristic->setValue(&txValue, 1); pCharacteristic->notify(); txValue++; delay(10); // bluetooth stack will go into congestion, if too many packets are sent } if (!deviceConnected && oldDeviceConnected) { delay(500); // give the bluetooth stack the chance to get things ready pServer->startAdvertising(); // restart advertising Serial.println("start advertising"); oldDeviceConnected = deviceConnected; } if (deviceConnected && !oldDeviceConnected) { // do stuff here on connecting oldDeviceConnected = deviceConnected; } } ``` 2. 接下来,需要在Arduino上编写蓝牙客户端代码。以下是一个简单的代码片段,演示了如何在Arduino上连接到ESP32蓝牙服务器并发送数据: ```c++ #include <SoftwareSerial.h> SoftwareSerial BTSerial(10, 11); // RX | TX void setup() { Serial.begin(9600); BTSerial.begin(9600); // HC-05 default speed in AT command more } void loop() { if (BTSerial.available()) { Serial.write(BTSerial.read()); } if (Serial.available()) { BTSerial.write(Serial.read()); } } ``` 在这个例子中,Arduino使用SoftwareSerial库将数据发送到ESP32蓝牙服务器。可以使用Serial Monitor来查看从ESP32返回的数据。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值