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

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

嵌入式QT开发:构建高效智能的嵌入式系统

摘要: 本文深入探讨了嵌入式 QT 相关的各个方面。从 QT 框架的基础架构和核心概念出发,详细阐述了其在嵌入式环境中的优势与特点。文中分析了嵌入式 QT 的开发环境搭建过程,包括交叉编译工具链的配置等关键步骤。进一步探讨了嵌入式 QT 的界面设计与开发,涵盖了从基本控件的使用到复杂界面布局的构建。同时也深入研究了信号与槽机制在嵌入式系统中的应用,以及嵌入式 QT 与硬件设备的交互,包括输入输出设

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

在JS中的设计模式的单例模式、策略模式、代理模式、原型模式浅讲

1. 单例模式(Singleton Pattern) 确保一个类只有一个实例,并提供一个全局访问点。 示例代码: class Singleton {constructor() {if (Singleton.instance) {return Singleton.instance;}Singleton.instance = this;this.data = [];}addData(value)