300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 轻松易懂arduino低功耗BLE蓝牙通信

轻松易懂arduino低功耗BLE蓝牙通信

时间:2018-12-09 13:56:58

相关推荐

轻松易懂arduino低功耗BLE蓝牙通信

今天我们介绍蓝牙通信的另一种方式--BLE(Bluetooth Low Energy,蓝牙低功耗)。

什么是BLE

在《无线通信3:HC05/HC06经典蓝牙BT模块》我们提到过经典蓝牙BT和蓝牙低功耗BLE的区别。顾名思义,低功耗蓝牙追求的是极低的功耗,它的主要应用场景是短距离、少数据量的传输场景,不像经典蓝牙那样通信时要一直保持连接,BLE可以只在传输数据时建立连接,空闲时进入睡眠模式来节能,这使BLE通信的功耗可以做的很低,功耗可以是经典蓝牙的百分之一。

BLE不但支持点对点传输,还支持广播模式、还可以组建Mesh网络。

BLE的特性,让它非常适合那些长时间靠电池供电,只偶尔发送少量数据的小设备。比如健康手环、追踪标签、物联网传感器等等。

BLE服务端和客户端

在BLE通信模式中,存在两类设备:BLE服务端(BLE Server)和BLE客户端(BLE Client)。通信时,BLE服务端向外发送信号,可以被附近的BLE客户端发现,一个BLE客户端可以连接特定的服务端,然后读取服务端发送的信号数据。

BLE数据结构:GATT

理解BLE通信还需要几个概念,最重要的就是GATT,GATT全称为Generic Attributes。可以简单地为BLE蓝牙通信的基础数据结构。

BLEService

GATT结构里最上层的是Profile,一个Profile包含至少一个BLE Service,通常一个BLE设备是包含多个Service的。这些BLE Service并不是随随便便自己可以设定的,而是由蓝牙技术联盟(Bluetooth Special Interest Group)为了规范而事先统一制定的。比如有显示电量的Service,还有心跳、血压、计重等等各种Service。

BLE Characteristic

每个Service下面包含一个或者多个特征(Characteristic),这些Characteristic包含特征的声明(Declaration)、数据值(Value)和描述符(Descriptor)。这些特征组成可以完整地描述一个Characteristic如何被使用,常见的操作如:

Broadcast

Read

Write without response

Write

Notify

Indicate

Authenticated Signed Writes

Extended Properties

UUID

在BLE GATT中,每个Service、每个Characteristic和每个Descriptor都有一个特定的128比特的UUID表示,就是类似下面的一串数字:

0x0000xxxx-0000-1000-8000-00805F9B34FB

为了简化,蓝牙技术联盟定义了16位UUID代替上面的基本UUID的‘x’部分。例如,心率测量特性使用0X2A37作为它的16位UUID,因此它完整的128位UUID为:

0x00002A37-0000-1000-8000-00805F9B34FB

值得注意的是蓝牙技术联盟所用的基本UUID不能用于任何自定义的属性、服务和特性。另外对于自定义UUID,必须使用另外完整的128位UUID。

如何用Arduino IDE开发BLE应用

在Arduino开发环境里开发BLE应用,我们一般有两种选择:

使用Arduino开发板配合BLE模块,类似经典蓝牙HC05/HC06模块,蓝牙低功耗也有比较流行的HM-10模块,HM-10模块是基于TI的CC2540/CC2541 BLE 4.0模组。Arduino开发板通过串口通信给HM-10发送AT命令来设置参数和收发数据。

使用ESP32这样的自带BLE功能且能用Arduino IDE开发的开发板。ESP32除了自带WiFi,还板载了蓝牙双模(经典蓝牙BT和蓝牙低功耗BLE),体积小价格也香。

如果你选择第一种,网上也有很多关于Arduino配合HM-10模块的使用教程,我们这里就不介绍了。在下面的实践中我们将使用ESP32作为我们的开发平台。

使用ESP32创建BLE Server

在使用ESP32开发板前,我们需要让Arduino IDE支持ESP32开发板,新手可以参考《ESP32-CAM打造低成本网络监控摄像头》一文中的“ 安装ESP32插件”一节。

安装成功后,选择DOIT DEVKIT V1板型,打开Arduino IDE的文件->示例里,我们就可以看到BLE相关的几个例子。我们打开BLE_server或者复制以下代码到IDE里:

/*BasedonNeilKolbanexampleforIDF:/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cppPortedtoArduinoESP32byEvandroCoperciniupdatesbychegewara*/#include<BLEDevice.h>#include<BLEUtils.h>#include<BLEServer.h>//SeethefollowingforgeneratingUUIDs:///#defineSERVICE_UUID"4fafc201-1fb5-459e-8fcc-c5c9c331914b"#defineCHARACTERISTIC_UUID"beb5483e-36e1-4688-b7f5-ea07361b26a8"voidsetup(){Serial.begin(115200);Serial.println("StartingBLEwork!");BLEDevice::init("MyESP32");BLEServer*pServer=BLEDevice::createServer();BLEService*pService=pServer->createService(SERVICE_UUID);BLECharacteristic*pCharacteristic=pService->createCharacteristic(CHARACTERISTIC_UUID,BLECharacteristic::PROPERTY_READ|BLECharacteristic::PROPERTY_WRITE);pCharacteristic->setValue("HelloWorldsaysNeil");pService->start();//BLEAdvertising*pAdvertising=pServer->getAdvertising();//thisstillisworkingforbackwardcompatibilityBLEAdvertising*pAdvertising=BLEDevice::getAdvertising();pAdvertising->addServiceUUID(SERVICE_UUID);pAdvertising->setScanResponse(true);pAdvertising->setMinPreferred(0x06);//functionsthathelpwithiPhoneconnectionsissuepAdvertising->setMinPreferred(0x12);BLEDevice::startAdvertising();Serial.println("Characteristicdefined!Nowyoucanreaditinyourphone!");}voidloop(){//putyourmaincodehere,torunrepeatedly:delay(2000);}

我们来过一遍代码,解释一下:

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

开头引入一些必要的BLE相关的库文件。

#defineSERVICE_UUID"4fafc201-1fb5-459e-8fcc-c5c9c331914b"#defineCHARACTERISTIC_UUID"beb5483e-36e1-4688-b7f5-ea07361b26a8"

然后我们需要定义服务(Service),特征(Characteristic)的UUID码,因为这里我们是自定义的服务和特征,所以首先我们不能使用跟蓝牙技术联盟规定重复的UUID,而且我们必须使用完整的128位UUID,为了方便我们可以使用一些在线随机生成UUID的网络服务:

/

在setup()里,建立串口通信,波特率设为115200。然后首先创建一个BLE设备,在参数里传入设备名,设备名可以随便取。

BLEDevice::init("BLEDevicename");

然后我们需要设置设备的模式为BLE Server:

BLEServer*pServer=BLEDevice::createServer();

接下去给这个Server添加一个Service,传入头部设置的Service UUID:

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

再为这个Service创建Characteristic,这里除了传入UUID,还要声明这个Characteristic的读写属性,这个例子里是可读可写:

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

然后给Characteristic赋个初始值。这个值可以被客户端读取然后改写。

pCharacteristic->setValue("HelloWorldsaysNeil");

最后,我们开启这个Service,然后开始广播。这样这个Server就可以被BLE的客户端扫描到。

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

这样,一个简单的BLE Server就创建成功了,编译上传就可以了,十分简单。

BLE Client端

BLE Server创建完成后,我们需要Client端来连接Server,并读写数据。在BLE应用中,Client端往往是手机,当然也可以是其他单片机。

下面我们就分别演示一下这两种方式。

方式一:单片机

如果使用单片机作为BLE Client,那么同样需要配合BLE模组或者单片机自带BLE功能,这里我们用另外一块ESP32演示。

我们打开Arduino IDE文件->示例里的BLE_client例子:

/***ABLEclientexamplethatisrichincapabilities.*/#include"BLEDevice.h"//#include"BLEScan.h"//Theremoteservicewewishtoconnectto.staticBLEUUIDserviceUUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");//Thecharacteristicoftheremoteserviceweareinterestedin.staticBLEUUIDcharUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");staticBLEAddress*pServerAddress;staticbooleandoConnect=false;staticbooleanconnected=false;staticBLERemoteCharacteristic*pRemoteCharacteristic;staticvoidnotifyCallback(BLERemoteCharacteristic*pBLERemoteCharacteristic,uint8_t*pData,size_tlength,boolisNotify){Serial.print("Notifycallbackforcharacteristic");Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());Serial.print("ofdatalength");Serial.println(length);}boolconnectToServer(BLEAddresspAddress){Serial.print("Formingaconnectionto");Serial.println(pAddress.toString().c_str());BLEClient*pClient=BLEDevice::createClient();Serial.println("-Createdclient");//ConnecttotheremoveBLEServer.pClient->connect(pAddress);Serial.println("-Connectedtoserver");//ObtainareferencetotheserviceweareafterintheremoteBLEserver.BLERemoteService*pRemoteService=pClient->getService(serviceUUID);if(pRemoteService==nullptr){Serial.print("FailedtofindourserviceUUID:");Serial.println(serviceUUID.toString().c_str());returnfalse;}Serial.println("-Foundourservice");//ObtainareferencetothecharacteristicintheserviceoftheremoteBLEserver.pRemoteCharacteristic=pRemoteService->getCharacteristic(charUUID);if(pRemoteCharacteristic==nullptr){Serial.print("FailedtofindourcharacteristicUUID:");Serial.println(charUUID.toString().c_str());returnfalse;}Serial.println("-Foundourcharacteristic");//Readthevalueofthecharacteristic.std::stringvalue=pRemoteCharacteristic->readValue();Serial.print("Thecharacteristicvaluewas:");Serial.println(value.c_str());pRemoteCharacteristic->registerForNotify(notifyCallback);}/***ScanforBLEserversandfindthefirstonethatadvertisestheservicewearelookingfor.*/classMyAdvertisedDeviceCallbacks:publicBLEAdvertisedDeviceCallbacks{/***CalledforeachadvertisingBLEserver.*/voidonResult(BLEAdvertisedDeviceadvertisedDevice){Serial.print("BLEAdvertisedDevicefound:");Serial.println(advertisedDevice.toString().c_str());//Wehavefoundadevice,letusnowseeifitcontainstheservicewearelookingfor.if(advertisedDevice.haveServiceUUID()&&advertisedDevice.getServiceUUID().equals(serviceUUID)){//Serial.print("Foundourdevice!address:");advertisedDevice.getScan()->stop();pServerAddress=newBLEAddress(advertisedDevice.getAddress());doConnect=true;}//Foundourserver}//onResult};//MyAdvertisedDeviceCallbacksvoidsetup(){Serial.begin(115200);Serial.println("StartingArduinoBLEClientapplication...");BLEDevice::init("");//RetrieveaScannerandsetthecallbackwewanttousetobeinformedwhenwe//havedetectedanewdevice.Specifythatwewantactivescanningandstartthe//scantorunfor30seconds.BLEScan*pBLEScan=BLEDevice::getScan();pBLEScan->setAdvertisedDeviceCallbacks(newMyAdvertisedDeviceCallbacks());pBLEScan->setActiveScan(true);pBLEScan->start(30);}//Endofsetup.//ThisistheArduinomainloopfunction.voidloop(){//Iftheflag"doConnect"istruethenwehavescannedforandfoundthedesired//BLEServerwithwhichwewishtoconnect.Nowweconnecttoit.Onceweare//connectedwesettheconnectedflagtobetrue.if(doConnect==true){if(connectToServer(*pServerAddress)){Serial.println("WearenowconnectedtotheBLEServer.");connected=true;}else{Serial.println("Wehavefailedtoconnecttotheserver;thereisnothinmorewewilldo.");}doConnect=false;}//IfweareconnectedtoapeerBLEServer,updatethecharacteristiceachtimewearereached//withthecurrenttimesinceboot.if(connected){StringnewValue="Timesinceboot:"+String(millis()/1000);Serial.println("Settingnewcharacteristicvalueto\""+newValue+"\"");//Setthecharacteristic'svaluetobethearrayofbytesthatisactuallyastring.pRemoteCharacteristic->writeValue(newValue.c_str(),newValue.length());}delay(1000);//Delayasecondbetweenloops.}//Endofloop

Client端代码稍微复杂些,但对应Server端也不难理解。在setup()中创建BLE设备并开启扫描模式,扫描附近所有的BLE Server。

找到一个Server就在Callback函数里对比Service和Characteristic的UUID码,对上后就停止扫描。在loop()函数里不断检查连接情况,并每次改写BLE Server的特征值。

BLE_Client示例演示了客户端如何扫描Server,并连接,对比UUID,读取并改写特征值的基本操作。

方式二:手机客户端

手机客户端配合BLE服务端是更常见的搭配,但关于手机APP如何调用系统蓝牙接口更多涉及的是手机移动端的编程:如果安卓系统你要懂Java和Android SDK,苹果系统则要懂Objective-C/Swift还有iOS的底层...总之又是另一个领域。如果你感兴趣,可以自行钻研,网上也不乏蓝牙APP开发的教程。这里我们使用Nordic半导体官方推出的BLE调试APP--nRF Connect来看看如何使用手机BLE Client如何查看我们之前创建的ESP32 BLE Server。

首先,我们在苹果商店或者安卓第三方商店搜索、下载并安装好nRF Connect。

打开APP后,我们就可以搜索附近的BLE设备,当然手机的蓝牙功能和相关权限要在设置里打开,否则APP会红字提示。

扫描一圈后,APP会列表显示所有扫描到的附近的BLE设备,找到我们自己命名的BLE Server点击Connect。

连接成功后,会跳转至设备页,里面详细罗列了这个Server所有的Services、Characteristic还有对应的UUID码。我们展开就可以看见自定义的特征值,也可以直接通过APP改写这个值。

结语

我们简单地介绍了蓝牙低功耗BLE和经典蓝牙BT的不同,BLE的数据结构,及如何用ESP32创建BLE的服务端和客户端。至此,蓝牙通信上下部分就完结了,在本系列的下一篇中,小编继续介绍Arduino无线通信里另外一个“半壁江山” -- WiFi通信。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。