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

相关文章

SpringBoot 多环境开发实战(从配置、管理与控制)

《SpringBoot多环境开发实战(从配置、管理与控制)》本文详解SpringBoot多环境配置,涵盖单文件YAML、多文件模式、MavenProfile分组及激活策略,通过优先级控制灵活切换环境... 目录一、多环境开发基础(单文件 YAML 版)(一)配置原理与优势(二)实操示例二、多环境开发多文件版

使用docker搭建嵌入式Linux开发环境

《使用docker搭建嵌入式Linux开发环境》本文主要介绍了使用docker搭建嵌入式Linux开发环境,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录1、前言2、安装docker3、编写容器管理脚本4、创建容器1、前言在日常开发全志、rk等不同

Python实战之SEO优化自动化工具开发指南

《Python实战之SEO优化自动化工具开发指南》在数字化营销时代,搜索引擎优化(SEO)已成为网站获取流量的重要手段,本文将带您使用Python开发一套完整的SEO自动化工具,需要的可以了解下... 目录前言项目概述技术栈选择核心模块实现1. 关键词研究模块2. 网站技术seo检测模块3. 内容优化分析模

基于Java开发一个极简版敏感词检测工具

《基于Java开发一个极简版敏感词检测工具》这篇文章主要为大家详细介绍了如何基于Java开发一个极简版敏感词检测工具,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录你是否还在为敏感词检测头疼一、极简版Java敏感词检测工具的3大核心优势1.1 优势1:DFA算法驱动,效率提升10

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

C#和Unity中的中介者模式使用方式

《C#和Unity中的中介者模式使用方式》中介者模式通过中介者封装对象交互,降低耦合度,集中控制逻辑,适用于复杂系统组件交互场景,C#中可用事件、委托或MediatR实现,提升可维护性与灵活性... 目录C#中的中介者模式详解一、中介者模式的基本概念1. 定义2. 组成要素3. 模式结构二、中介者模式的特点

Python学习笔记之getattr和hasattr用法示例详解

《Python学习笔记之getattr和hasattr用法示例详解》在Python中,hasattr()、getattr()和setattr()是一组内置函数,用于对对象的属性进行操作和查询,这篇文章... 目录1.getattr用法详解1.1 基本作用1.2 示例1.3 原理2.hasattr用法详解2.

Python开发简易网络服务器的示例详解(新手入门)

《Python开发简易网络服务器的示例详解(新手入门)》网络服务器是互联网基础设施的核心组件,它本质上是一个持续运行的程序,负责监听特定端口,本文将使用Python开发一个简单的网络服务器,感兴趣的小... 目录网络服务器基础概念python内置服务器模块1. HTTP服务器模块2. Socket服务器模块

Java 与 LibreOffice 集成开发指南(环境搭建及代码示例)

《Java与LibreOffice集成开发指南(环境搭建及代码示例)》本文介绍Java与LibreOffice的集成方法,涵盖环境配置、API调用、文档转换、UNO桥接及REST接口等技术,提供... 目录1. 引言2. 环境搭建2.1 安装 LibreOffice2.2 配置 Java 开发环境2.3 配

Python38个游戏开发库整理汇总

《Python38个游戏开发库整理汇总》文章介绍了多种Python游戏开发库,涵盖2D/3D游戏开发、多人游戏框架及视觉小说引擎,适合不同需求的开发者入门,强调跨平台支持与易用性,并鼓励读者交流反馈以... 目录PyGameCocos2dPySoyPyOgrepygletPanda3DBlenderFife