├── .gitignore ├── LICENSE ├── README.md ├── images ├── client_scan.png ├── demo.jpg └── nrf_connect_scan.png ├── lib └── readme.txt ├── platformio.ini └── src └── ESP32_BLE_client_uart.ino /.gitignore: -------------------------------------------------------------------------------- 1 | .pioenvs 2 | .piolibdeps 3 | .clang_complete 4 | .gcc-flags.json 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ESP32_BLE_client_uart 2 | ### Central mode (client) BLE UART for ESP32 3 | 4 | This sketch is a central mode (client) Nordic UART Service that connects automatically to a peripheral (server) Nordic UART Service. NUS is what most typical "blueart" servers emulate. This sketch will connect to your BLE uart device in the same manner the nRF Connect app does. 5 | 6 | Once connected, this sketch will switch notification on using BLE2902 for the charUUID_TX characteristic which is the characteristic that our server is making data available on via notification. The data received from the server characteristic charUUID_TX will be printed to Serial on this device. Every five seconds this device will send the string "Time since boot: #" to the server characteristic charUUID_RX, this will make that data available in the BLE uart and trigger a notifyCallback or similar depending on your BLE uart server setup. 7 | 8 | 9 | A brief explanation of BLE client/server actions and rolls: 10 | 11 | ##### Central Mode (client) - Connects to a peripheral (server). 12 | * Scans for devices and reads service UUID. 13 | * Connects to a server's address with the desired service UUID. 14 | * Checks for and makes a reference to one or more characteristic UUID in the current service. 15 | * The client can send data to the server by writing to this RX Characteristic. 16 | * If the client has enabled notifications for the TX characteristic, the server can send data to the client as notifications to that characteristic. This will trigger the notifyCallback function. 17 | 18 | ##### Peripheral (server) - Accepts connections from a central mode device (client). 19 | * Advertises a service UUID. 20 | * Creates one or more characteristic for the advertised service UUID 21 | * Accepts connections from a client. 22 | * The server can send data to the client by writing to this TX Characteristic. 23 | * If the server has enabled notifications for the RX characteristic, the client can send data to the server as notifications to that characteristic. This the default function on most "Nordic UART Service" BLE uart sketches. 24 | 25 | 26 | ### Testing 27 | Pictured below is the demo setup I tested this code on. The server is an nRF52 bluefruit feather with various sensors and an OLED. The client is a cheap ESP32 board with integrated OLED "Heltec WiFi Kit 32". Two way communication between both devices works as intended. 28 | 29 | ![demo](https://github.com/ThingEngineer/ESP32_BLE_client_uart/raw/master/images/demo.jpg) 30 | 31 | ### Issues with BLE_uart 32 | I also tried programing another ESP board "ESP32 Dev Module V1.0" with the BLE_uart sketch but this client will not connect to it. As you can see in the photos below, BLE_uart does not appear to be properly advertising the service UUID. You can see the device and it does work once you connect with the app but the client does not see the service UUID advertised in the scan so it never attempts a connection. If someone wants to tackle this I'd be glad to test it again with the fix. 33 | 34 | I also noticed that none of the other BLE_* server sketches advertised a serviceUUID that is visible in a scan. 35 | 36 | ![nRF Connect Scan](https://github.com/ThingEngineer/ESP32_BLE_client_uart/raw/master/images/nrf_connect_scan.png) 37 | 38 | ![BLE Client Scan](https://github.com/ThingEngineer/ESP32_BLE_client_uart/raw/master/images/client_scan.png) 39 | 40 | Based on the "BLE_Client" example by Neil Kolban: 41 | https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLETests/Arduino/BLE_client/BLE_client.ino 42 | 43 | With help from an example by Andreas Spiess: 44 | https://github.com/SensorsIot/Bluetooth-BLE-on-Arduino-IDE/blob/master/Polar_Receiver/Polar_Receiver.ino 45 | 46 | The BLE_uart sketch that does not advertise serviceUUID properly: 47 | https://github.com/nkolban/ESP32_BLE_Arduino/blob/master/examples/BLE_uart/BLE_uart.ino 48 | 49 | Nordic UART Service info: 50 | https://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.sdk5.v14.0.0%2Fble_sdk_app_nus_eval.html 51 | -------------------------------------------------------------------------------- /images/client_scan.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThingEngineer/ESP32_BLE_client_uart/fa31fbb544f7ae0fea126b38e305d411888268d6/images/client_scan.png -------------------------------------------------------------------------------- /images/demo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThingEngineer/ESP32_BLE_client_uart/fa31fbb544f7ae0fea126b38e305d411888268d6/images/demo.jpg -------------------------------------------------------------------------------- /images/nrf_connect_scan.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ThingEngineer/ESP32_BLE_client_uart/fa31fbb544f7ae0fea126b38e305d411888268d6/images/nrf_connect_scan.png -------------------------------------------------------------------------------- /lib/readme.txt: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for project specific (private) libraries. 3 | PlatformIO will compile them to static libraries and link them to executable files. 4 | 5 | The source code of each library should be placed in separate directories, like 6 | "lib/private_lib/[here are source files]". 7 | 8 | For example, see the structure of the following two libraries `Foo` and `Bar`: 9 | 10 | |--lib 11 | | | 12 | | |--Bar 13 | | | |--docs 14 | | | |--examples 15 | | | |--src 16 | | | |- Bar.c 17 | | | |- Bar.h 18 | | | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html 19 | | | 20 | | |--Foo 21 | | | |- Foo.c 22 | | | |- Foo.h 23 | | | 24 | | |- readme.txt --> THIS FILE 25 | | 26 | |- platformio.ini 27 | |--src 28 | |- main.c 29 | 30 | Then in `src/main.c` you should use: 31 | 32 | #include 33 | #include 34 | 35 | // rest H/C/CPP code 36 | 37 | PlatformIO will find your libraries automatically, configure preprocessor's 38 | include paths and build them. 39 | 40 | More information about PlatformIO Library Dependency Finder 41 | - https://docs.platformio.org/page/librarymanager/ldf.html 42 | -------------------------------------------------------------------------------- /platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [env:esp32dev] 12 | platform = espressif32 13 | board = esp32dev 14 | framework = arduino 15 | upload_port = /dev/cu.SLAB_USBtoUART179 16 | -------------------------------------------------------------------------------- /src/ESP32_BLE_client_uart.ino: -------------------------------------------------------------------------------- 1 | /* Central Mode (client) BLE UART for ESP32 2 | * 3 | * This sketch is a central mode (client) Nordic UART Service (NUS) that connects automatically to a peripheral (server) 4 | * Nordic UART Service. NUS is what most typical "blueart" servers emulate. This sketch will connect to your BLE uart 5 | * device in the same manner the nRF Connect app does. 6 | * 7 | * Once connected this sketch will switch notification on using BLE2902 for the charUUID_TX characteristic which is the 8 | * characteristic that our server is making data available on via notification. The data received from the server 9 | * characteristic charUUID_TX will be printed to Serial on this device. Every five seconds this device will send the 10 | * string "Time since boot: #" to the server characteristic charUUID_RX, this will make that data available in the BLE 11 | * uart and trigger a notifyCallback or similar depending on your BLE uart server setup. 12 | * 13 | * 14 | * A brief explanation of BLE client/server actions and rolls: 15 | * 16 | * Central Mode (client) - Connects to a peripheral (server). 17 | * -Scans for devices and reads service UUID. 18 | * -Connects to a server's address with the desired service UUID. 19 | * -Checks for and makes a reference to one or more characteristic UUID in the current service. 20 | * -The client can send data to the server by writing to this RX Characteristic. 21 | * -If the client has enabled notifications for the TX characteristic, the server can send data to the client as 22 | * notifications to that characteristic. This will trigger the notifyCallback function. 23 | * 24 | * Peripheral (server) - Accepts connections from a central mode device (client). 25 | * -Advertises a service UUID. 26 | * -Creates one or more characteristic for the advertised service UUID 27 | * -Accepts connections from a client. 28 | * -The server can send data to the client by writing to this TX Characteristic. 29 | * -If the server has enabled notifications for the RX characteristic, the client can send data to the server as 30 | * notifications to that characteristic. This the default function on most "Nordic UART Service" BLE uart sketches. 31 | * 32 | * 33 | * Copyright <2018> 34 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 35 | * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the 36 | * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 37 | * permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright 38 | * notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 39 | * SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 40 | * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 41 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 42 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 43 | * 44 | * 45 | * Based on the "BLE_Client" example by Neil Kolban: 46 | * https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLETests/Arduino/BLE_client/BLE_client.ino 47 | * With help from an example by Andreas Spiess: 48 | * https://github.com/SensorsIot/Bluetooth-BLE-on-Arduino-IDE/blob/master/Polar_Receiver/Polar_Receiver.ino 49 | * Nordic UART Service info: 50 | * https://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.sdk5.v14.0.0%2Fble_sdk_app_nus_eval.html 51 | * 52 | */ 53 | 54 | 55 | #include "BLEDevice.h" 56 | 57 | 58 | // The remote Nordic UART service service we wish to connect to. 59 | // This service exposes two characteristics: one for transmitting and one for receiving (as seen from the client). 60 | static BLEUUID serviceUUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"); 61 | 62 | // The characteristics of the above service we are interested in. 63 | // The client can send data to the server by writing to this characteristic. 64 | static BLEUUID charUUID_RX("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"); // RX Characteristic 65 | 66 | // If the client has enabled notifications for this characteristic, 67 | // the server can send data to the client as notifications. 68 | static BLEUUID charUUID_TX("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"); // TX Characteristic 69 | 70 | static BLEAddress *pServerAddress; 71 | static boolean doConnect = false; 72 | static boolean connected = false; 73 | static BLERemoteCharacteristic* pTXCharacteristic; 74 | static BLERemoteCharacteristic* pRXCharacteristic; 75 | 76 | static void notifyCallback( 77 | BLERemoteCharacteristic* pBLERemoteCharacteristic, 78 | uint8_t* pData, 79 | size_t length, 80 | bool isNotify) { 81 | Serial.println("Notify callback for TX characteristic received. Data:"); 82 | for (int i = 0; i < length; i++) { 83 | // Serial.print((char)pData[i]); // Print character to uart 84 | Serial.print(pData[i]); // print raw data to uart 85 | Serial.print(" "); 86 | } 87 | Serial.println(); 88 | } 89 | 90 | bool connectToServer(BLEAddress pAddress) { 91 | Serial.print("Establishing a connection to device address: "); 92 | Serial.println(pAddress.toString().c_str()); 93 | 94 | BLEClient* pClient = BLEDevice::createClient(); 95 | Serial.println(" - Created client"); 96 | 97 | // Connect to the remove BLE Server. 98 | pClient->connect(pAddress); 99 | Serial.println(" - Connected to server"); 100 | 101 | // Obtain a reference to the Nordic UART service on the remote BLE server. 102 | BLERemoteService* pRemoteService = pClient->getService(serviceUUID); 103 | if (pRemoteService == nullptr) { 104 | Serial.print("Failed to find Nordic UART service UUID: "); 105 | Serial.println(serviceUUID.toString().c_str()); 106 | return false; 107 | } 108 | Serial.println(" - Remote BLE service reference established"); 109 | 110 | 111 | // Obtain a reference to the TX characteristic of the Nordic UART service on the remote BLE server. 112 | pTXCharacteristic = pRemoteService->getCharacteristic(charUUID_TX); 113 | if (pTXCharacteristic == nullptr) { 114 | Serial.print("Failed to find TX characteristic UUID: "); 115 | Serial.println(charUUID_TX.toString().c_str()); 116 | return false; 117 | } 118 | Serial.println(" - Remote BLE TX characteristic reference established"); 119 | 120 | // Read the value of the TX characteristic. 121 | std::string value = pTXCharacteristic->readValue(); 122 | Serial.print("The characteristic value is currently: "); 123 | Serial.println(value.c_str()); 124 | 125 | pTXCharacteristic->registerForNotify(notifyCallback); 126 | 127 | // Obtain a reference to the RX characteristic of the Nordic UART service on the remote BLE server. 128 | pRXCharacteristic = pRemoteService->getCharacteristic(charUUID_RX); 129 | if (pRXCharacteristic == nullptr) { 130 | Serial.print("Failed to find our characteristic UUID: "); 131 | Serial.println(charUUID_RX.toString().c_str()); 132 | return false; 133 | } 134 | Serial.println(" - Remote BLE RX characteristic reference established"); 135 | 136 | // Write to the the RX characteristic. 137 | String helloValue = "Hello Remote Server"; 138 | pRXCharacteristic->writeValue(helloValue.c_str(), helloValue.length()); 139 | } 140 | 141 | 142 | /** 143 | Scan for BLE servers and find the first one that advertises the Nordic UART service. 144 | */ 145 | class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { 146 | /** 147 | Called for each advertising BLE server. 148 | */ 149 | void onResult(BLEAdvertisedDevice advertisedDevice) { 150 | Serial.print("BLE Advertised Device found - "); 151 | Serial.println(advertisedDevice.toString().c_str()); 152 | 153 | // We have found a device, check to see if it contains the Nordic UART service. 154 | if (advertisedDevice.haveServiceUUID() && advertisedDevice.getServiceUUID().equals(serviceUUID)) { 155 | 156 | Serial.println("Found a device with the desired ServiceUUID!"); 157 | advertisedDevice.getScan()->stop(); 158 | 159 | pServerAddress = new BLEAddress(advertisedDevice.getAddress()); 160 | doConnect = true; 161 | 162 | } // Found our server 163 | } // onResult 164 | }; // MyAdvertisedDeviceCallbacks 165 | 166 | 167 | void setup() { 168 | Serial.begin(115200); 169 | Serial.println("Starting Arduino BLE Central Mode (Client) Nordic UART Service"); 170 | 171 | BLEDevice::init(""); 172 | 173 | // Retrieve a Scanner and set the callback we want to use to be informed when we 174 | // have detected a new device. Specify that we want active scanning and start the 175 | // scan to run for 30 seconds. 176 | BLEScan* pBLEScan = BLEDevice::getScan(); 177 | pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); 178 | pBLEScan->setActiveScan(true); 179 | pBLEScan->start(30); 180 | } // End of setup. 181 | 182 | 183 | const uint8_t notificationOff[] = {0x0, 0x0}; 184 | const uint8_t notificationOn[] = {0x1, 0x0}; 185 | bool onoff = true; 186 | 187 | void loop() { 188 | 189 | // If the flag "doConnect" is true then we have scanned for and found the desired 190 | // BLE Server with which we wish to connect. Now we connect to it. Once we are 191 | // connected we set the connected flag to be true. 192 | if (doConnect == true) { 193 | if (connectToServer(*pServerAddress)) { 194 | Serial.println("We are now connected to the BLE Server."); 195 | connected = true; 196 | } else { 197 | Serial.println("We have failed to connect to the server; there is nothin more we will do."); 198 | } 199 | doConnect = false; 200 | } 201 | 202 | // If we are connected to a peer BLE Server perform the following actions every five seconds: 203 | // Toggle notifications for the TX Characteristic on and off. 204 | // Update the RX characteristic with the current time since boot string. 205 | if (connected) { 206 | if (onoff) { 207 | Serial.println("Notifications turned on"); 208 | pTXCharacteristic->getDescriptor(BLEUUID((uint16_t)0x2902))->writeValue((uint8_t*)notificationOn, 2, true); 209 | } else { 210 | Serial.println("Notifications turned off"); 211 | pTXCharacteristic->getDescriptor(BLEUUID((uint16_t)0x2902))->writeValue((uint8_t*)notificationOff, 2, true); 212 | } 213 | 214 | // Toggle on/off value for notifications. 215 | onoff = onoff ? 0 : 1; 216 | 217 | // Set the characteristic's value to be the array of bytes that is actually a string 218 | String timeSinceBoot = "Time since boot: " + String(millis()/1000); 219 | pRXCharacteristic->writeValue(timeSinceBoot.c_str(), timeSinceBoot.length()); 220 | } 221 | 222 | delay(5000); // Delay five seconds between loops. 223 | } // End of loop 224 | --------------------------------------------------------------------------------