nRF52832-Bluefruit52学习之Arduino开发(4)-- 蓝牙组网一拖8主从机模式(dual_roles_bleuart)

本文主要是介绍nRF52832-Bluefruit52学习之Arduino开发(4)-- 蓝牙组网一拖8主从机模式(dual_roles_bleuart),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

       nRF52832技术交流群:680723714

       nRF52832-Bluefruit52核心板详细介绍:

https://blog.csdn.net/solar_Lan/article/details/88688451

       github仓库地址:https://github.com/Afantor/Bluefruit52_Arduino.git

       

       Arduino例程目前分为6大部分:Central、DualRoles、Display、Hardware、Peripheral、Project。

一、Central:主设备与其他设备通信例程

二、DualRoles:从设备与主设备通信例程

本篇讲解蓝牙组网一拖8实验,本实验展示了以一个nRF52382为中心,其他nRF52832模块为外围设备,进行级联通信控制的过程。示例中演示串口打印连接状态和接收到数据,通过数据收发控制板载LED灯。主机中心为一个主模式设备,检测按键发送控制LED的字符。从设备检测接收到的数据,控制LED灯的状态。

下面直接讲解代码:

Dual Roles BLEUART双重角色BLEUART

如果不熟悉中心角色,建议先查看“Central BLEUART”示例,和上一篇博文然后再继续。
此示例演示了如何使用nRF52832同时使用bleuart(AKA'NUS')服务连接其他7个Bluefruit或BLE设备,同时设备在外围设备和中心设备上运行。

此双重角色示例充当BLE中继站,它位于中央和外围转发前端消息之间来回,如下图所示:

microcontrollers_dual_roles.jpg

Server & Client Service Setup服务端和客户端设置

由于Bluefruit设备将充当中心和外围设备,因此我们需要声明bleuart帮助程序类的服务器和客户端实例:

// Peripheral uart service
BLEUart bleuart;// Central uart client
BLEClientUart clientUart;

在我们配置客户端服务之前,必须至少调用Bluefruit.begin(),以获得外围和中央模式的并发连接数:

// Initialize Bluefruit with max concurrent connections as Peripheral = 1, Central = 1
Bluefruit.begin(1, 1);

在此之后,必须通过调用其begin()函数初始化客户端服务,然后调用您希望连接的任何回调:

// Configure and Start BLE Uart Service
bleuart.begin();
bleuart.setRxCallback(prph_bleuart_rx_callback);// Init BLE Central Uart Serivce
clientUart.begin();
clientUart.setRxCallback(cent_bleuart_rx_callback);

然后我们准备使用回调将数据从中央转发到外围,反之亦然:

void cent_bleuart_rx_callback(BLEClientUart& cent_uart)
{char str[20+1] = { 0 };cent_uart.read(str, 20);Serial.print("[Cent] RX: ");Serial.println(str);if ( bleuart.notifyEnabled() ){// Forward data from our peripheral to Mobilebleuart.print( str );}else{// response with no prph messageclientUart.println("[Cent] Peripheral role not connected");}  
}void prph_bleuart_rx_callback(void)
{// Forward data from Mobile to our peripheralchar str[20+1] = { 0 };bleuart.read(str, 20);Serial.print("[Prph] RX: ");Serial.println(str);  if ( clientUart.discovered() ){clientUart.print(str);}else{bleuart.println("[Prph] Central role not connected");}
}

Peripheral Role外设角色

我们代码的外围部分要做的第一件事就是设置连接回调,当与中心建立/断开连接时,它会触发。 或者,您可以使用connected()轮询连接状态,但回调有助于显着简化代码:

// Callbacks for Peripheral
Bluefruit.setConnectCallback(prph_connect_callback);
Bluefruit.setDisconnectCallback(prph_disconnect_callback);

Central Role中心角色

接下来,我们设置中央模式连接回调,当与外围设备建立/断开连接时将触发:

// Callbacks for Central
Bluefruit.Central.setConnectCallback(cent_connect_callback);
Bluefruit.Central.setDisconnectCallback(cent_disconnect_callback);

Advertising and Scanner广播和扫描

可以同时启动扫描仪和广告,以便我们可以发现并被其他BLE设备发现。 对于扫描程序,如果在对等设备的广告数据中找到特定的UUID,我们使用仅触发回调的过滤器:

/* Start Central Scanning* - Enable auto scan if disconnected* - Interval = 100 ms, window = 80 ms* - Filter only accept bleuart service* - Don't use active scan* - Start(timeout) with timeout = 0 will scan forever (until connected)*/
Bluefruit.Scanner.setRxCallback(scan_callback);
Bluefruit.Scanner.restartOnDisconnect(true);
Bluefruit.Scanner.setInterval(160, 80); // in unit of 0.625 ms
Bluefruit.Scanner.filterUuid(bleuart.uuid);
Bluefruit.Scanner.useActiveScan(false);
Bluefruit.Scanner.start(0);                   // 0 = Don't stop scanning after n seconds// Advertising packet
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();// Include bleuart 128-bit uuid
Bluefruit.Advertising.addService(bleuart);// Secondary Scan Response packet (optional)
// Since there is no room for 'Name' in Advertising packet
Bluefruit.ScanResponse.addName();/* Start Advertising* - Enable auto advertising if disconnected* - Interval:  fast mode = 20 ms, slow mode = 152.5 ms* - Timeout for fast mode is 30 seconds* - Start(timeout) with timeout = 0 will advertise forever (until connected)** For recommended advertising interval* https://developer.apple.com/library/content/qa/qa1931/_index.html*/
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.setInterval(32, 244);    // in unit of 0.625 ms
Bluefruit.Advertising.setFastTimeout(30);      // number of seconds in fast mode
Bluefruit.Advertising.start(0);                // 0 = Don't stop advertising after n seconds

例程的完整代码:

/*********************************************************************This is an example for our nRF52 based Bluefruit LE modulesPick one up today in the adafruit shop!Adafruit invests time and resources providing this open source code,please support Adafruit and open-source hardware by purchasingproducts from Adafruit!MIT license, check LICENSE for more informationAll text above, and the splash screen below must be included inany redistribution
*********************************************************************//** This sketch demonstrate how to run both Central and Peripheral roles* at the same time. It will act as a relay between an central (mobile)* to another peripheral using bleuart service.* * Mobile <--> DualRole <--> peripheral Ble Uart*/
#include <bluefruit.h>// OTA DFU service
BLEDfu bledfu;// Peripheral uart service
BLEUart bleuart;// Central uart client
BLEClientUart clientUart;void setup()
{Serial.begin(115200);while ( !Serial ) delay(10);   // for nrf52840 with native usbSerial.println("Bluefruit52 Dual Role BLEUART Example");Serial.println("-------------------------------------\n");// Initialize Bluefruit with max concurrent connections as Peripheral = 1, Central = 1// SRAM usage required by SoftDevice will increase with number of connectionsBluefruit.begin(1, 1);Bluefruit.setTxPower(4);    // Check bluefruit.h for supported valuesBluefruit.setName("Bluefruit52 duo");// Callbacks for PeripheralBluefruit.Periph.setConnectCallback(prph_connect_callback);Bluefruit.Periph.setDisconnectCallback(prph_disconnect_callback);// Callbacks for CentralBluefruit.Central.setConnectCallback(cent_connect_callback);Bluefruit.Central.setDisconnectCallback(cent_disconnect_callback);// To be consistent OTA DFU should be added first if it existsbledfu.begin();// Configure and Start BLE Uart Servicebleuart.begin();bleuart.setRxCallback(prph_bleuart_rx_callback);// Init BLE Central Uart SerivceclientUart.begin();clientUart.setRxCallback(cent_bleuart_rx_callback);/* Start Central Scanning* - Enable auto scan if disconnected* - Interval = 100 ms, window = 80 ms* - Filter only accept bleuart service* - Don't use active scan* - Start(timeout) with timeout = 0 will scan forever (until connected)*/Bluefruit.Scanner.setRxCallback(scan_callback);Bluefruit.Scanner.restartOnDisconnect(true);Bluefruit.Scanner.setInterval(160, 80); // in unit of 0.625 msBluefruit.Scanner.filterUuid(bleuart.uuid);Bluefruit.Scanner.useActiveScan(false);Bluefruit.Scanner.start(0);                   // 0 = Don't stop scanning after n seconds// Set up and start advertisingstartAdv();
}void startAdv(void)
{// Advertising packetBluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);Bluefruit.Advertising.addTxPower();// Include bleuart 128-bit uuidBluefruit.Advertising.addService(bleuart);// Secondary Scan Response packet (optional)// Since there is no room for 'Name' in Advertising packetBluefruit.ScanResponse.addName();/* Start Advertising* - Enable auto advertising if disconnected* - Interval:  fast mode = 20 ms, slow mode = 152.5 ms* - Timeout for fast mode is 30 seconds* - Start(timeout) with timeout = 0 will advertise forever (until connected)** For recommended advertising interval* https://developer.apple.com/library/content/qa/qa1931/_index.html*/Bluefruit.Advertising.restartOnDisconnect(true);Bluefruit.Advertising.setInterval(32, 244);    // in unit of 0.625 msBluefruit.Advertising.setFastTimeout(30);      // number of seconds in fast modeBluefruit.Advertising.start(0);                // 0 = Don't stop advertising after n seconds
}void loop()
{// do nothing, all the work is done in callback
}/*------------------------------------------------------------------*/
/* Peripheral*------------------------------------------------------------------*/
void prph_connect_callback(uint16_t conn_handle)
{// Get the reference to current connectionBLEConnection* connection = Bluefruit.Connection(conn_handle);char peer_name[32] = { 0 };connection->getPeerName(peer_name, sizeof(peer_name));Serial.print("[Prph] Connected to ");Serial.println(peer_name);
}void prph_disconnect_callback(uint16_t conn_handle, uint8_t reason)
{(void) conn_handle;(void) reason;Serial.println();Serial.println("[Prph] Disconnected");
}void prph_bleuart_rx_callback(uint16_t conn_handle)
{(void) conn_handle;// Forward data from Mobile to our peripheralchar str[20+1] = { 0 };bleuart.read(str, 20);Serial.print("[Prph] RX: ");Serial.println(str);  if ( clientUart.discovered() ){clientUart.print(str);}else{bleuart.println("[Prph] Central role not connected");}
}/*------------------------------------------------------------------*/
/* Central*------------------------------------------------------------------*/
void scan_callback(ble_gap_evt_adv_report_t* report)
{// Since we configure the scanner with filterUuid()// Scan callback only invoked for device with bleuart service advertised  // Connect to the device with bleuart service in advertising packet  Bluefruit.Central.connect(report);
}void cent_connect_callback(uint16_t conn_handle)
{// Get the reference to current connectionBLEConnection* connection = Bluefruit.Connection(conn_handle);char peer_name[32] = { 0 };connection->getPeerName(peer_name, sizeof(peer_name));Serial.print("[Cent] Connected to ");Serial.println(peer_name);;if ( clientUart.discover(conn_handle) ){// Enable TXD's notifyclientUart.enableTXD();}else{// disconnect since we couldn't find bleuart serviceBluefruit.disconnect(conn_handle);}  
}void cent_disconnect_callback(uint16_t conn_handle, uint8_t reason)
{(void) conn_handle;(void) reason;Serial.println("[Cent] Disconnected");
}/*** Callback invoked when uart received data* @param cent_uart Reference object to the service where the data * arrived. In this example it is clientUart*/
void cent_bleuart_rx_callback(BLEClientUart& cent_uart)
{char str[20+1] = { 0 };cent_uart.read(str, 20);Serial.print("[Cent] RX: ");Serial.println(str);if ( bleuart.notifyEnabled() ){// Forward data from our peripheral to Mobilebleuart.print( str );}else{// response with no prph messageclientUart.println("[Cent] Peripheral role not connected");}  
}

 

这篇关于nRF52832-Bluefruit52学习之Arduino开发(4)-- 蓝牙组网一拖8主从机模式(dual_roles_bleuart)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/621468

相关文章

Android开发中gradle下载缓慢的问题级解决方法

《Android开发中gradle下载缓慢的问题级解决方法》本文介绍了解决Android开发中Gradle下载缓慢问题的几种方法,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、网络环境优化二、Gradle版本与配置优化三、其他优化措施针对android开发中Gradle下载缓慢的问

使用Go语言开发一个命令行文件管理工具

《使用Go语言开发一个命令行文件管理工具》这篇文章主要为大家详细介绍了如何使用Go语言开发一款命令行文件管理工具,支持批量重命名,删除,创建,移动文件,需要的小伙伴可以了解下... 目录一、工具功能一览二、核心代码解析1. 主程序结构2. 批量重命名3. 批量删除4. 创建文件/目录5. 批量移动三、如何安

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

Java实现状态模式的示例代码

《Java实现状态模式的示例代码》状态模式是一种行为型设计模式,允许对象根据其内部状态改变行为,本文主要介绍了Java实现状态模式的示例代码,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来... 目录一、简介1、定义2、状态模式的结构二、Java实现案例1、电灯开关状态案例2、番茄工作法状态案例

基于Python开发PPTX压缩工具

《基于Python开发PPTX压缩工具》在日常办公中,PPT文件往往因为图片过大而导致文件体积过大,不便于传输和存储,所以本文将使用Python开发一个PPTX压缩工具,需要的可以了解下... 目录引言全部代码环境准备代码结构代码实现运行结果引言在日常办公中,PPT文件往往因为图片过大而导致文件体积过大,

使用DeepSeek API 结合VSCode提升开发效率

《使用DeepSeekAPI结合VSCode提升开发效率》:本文主要介绍DeepSeekAPI与VisualStudioCode(VSCode)结合使用,以提升软件开发效率,具有一定的参考价值... 目录引言准备工作安装必要的 VSCode 扩展配置 DeepSeek API1. 创建 API 请求文件2.

基于Python开发电脑定时关机工具

《基于Python开发电脑定时关机工具》这篇文章主要为大家详细介绍了如何基于Python开发一个电脑定时关机工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 简介2. 运行效果3. 相关源码1. 简介这个程序就像一个“忠实的管家”,帮你按时关掉电脑,而且全程不需要你多做

Redis主从/哨兵机制原理分析

《Redis主从/哨兵机制原理分析》本文介绍了Redis的主从复制和哨兵机制,主从复制实现了数据的热备份和负载均衡,而哨兵机制可以监控Redis集群,实现自动故障转移,哨兵机制通过监控、下线、选举和故... 目录一、主从复制1.1 什么是主从复制1.2 主从复制的作用1.3 主从复制原理1.3.1 全量复制

Java中的Opencv简介与开发环境部署方法

《Java中的Opencv简介与开发环境部署方法》OpenCV是一个开源的计算机视觉和图像处理库,提供了丰富的图像处理算法和工具,它支持多种图像处理和计算机视觉算法,可以用于物体识别与跟踪、图像分割与... 目录1.Opencv简介Opencv的应用2.Java使用OpenCV进行图像操作opencv安装j