当前位置:   article > 正文

【IoT】Arduino 实现 ESP32 BLE 与 Android 手机的数据交互_arduino发送数据到手机app蓝牙代码

arduino发送数据到手机app蓝牙代码

1、效果描述:

通过简单的 Android APP 实现与 ESP32 的双向蓝牙通信。

2、实现步骤

Step 1:ESP32 硬件支持

1、支持蓝牙 4.0 以上协议的安卓手机;

2、支持 Micro USB 的 ESP32 dev board;

Step 2:配置 Arduino IDE 环境

1、下载 Arduino IDE:https://www.arduino.cc/en/Main/Software;

2、安装 ESP32 支持包:https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/windows.md

根据网站步骤安装 GIT 工具,并根据提示下载 BLE 支持开发包

在 Arduino 编写实例:

  1. /*
  2. Video: https://www.youtube.com/watch?v=oCMOYS71NIU
  3. Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp
  4. Ported to Arduino ESP32 by Evandro Copercini
  5. Create a BLE server that, once we receive a connection, will send periodic notifications.
  6. The service advertises itself as: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E
  7. Has a characteristic of: 6E400002-B5A3-F393-E0A9-E50E24DCCA9E - used for receiving data with "WRITE"
  8. Has a characteristic of: 6E400003-B5A3-F393-E0A9-E50E24DCCA9E - used to send data with "NOTIFY"
  9. The design of creating the BLE server is:
  10. 1. Create a BLE Server
  11. 2. Create a BLE Service
  12. 3. Create a BLE Characteristic on the Service
  13. 4. Create a BLE Descriptor on the characteristic
  14. 5. Start the service.
  15. 6. Start advertising.
  16. In this example rxValue is the data received (only accessible inside that function).
  17. And txValue is the data to be sent, in this example just a byte incremented every second.
  18. */
  19. #include <BLEDevice.h>
  20. #include <BLEServer.h>
  21. #include <BLEUtils.h>
  22. #include <BLE2902.h>
  23. BLECharacteristic *pCharacteristic;
  24. bool deviceConnected = false;
  25. float txValue = 0;
  26. const int readPin = 32; // Use GPIO number. See ESP32 board pinouts
  27. const int LED = 2; // Could be different depending on the dev board. I used the DOIT ESP32 dev board.
  28. //std::string rxValue; // Could also make this a global var to access it in loop()
  29. // See the following for generating UUIDs:
  30. // https://www.uuidgenerator.net/
  31. #define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
  32. #define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
  33. #define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
  34. class MyServerCallbacks: public BLEServerCallbacks {
  35. void onConnect(BLEServer* pServer) {
  36. deviceConnected = true;
  37. };
  38. void onDisconnect(BLEServer* pServer) {
  39. deviceConnected = false;
  40. }
  41. };
  42. class MyCallbacks: public BLECharacteristicCallbacks {
  43. void onWrite(BLECharacteristic *pCharacteristic) {
  44. std::string rxValue = pCharacteristic->getValue();
  45. if (rxValue.length() > 0) {
  46. Serial.println("*********");
  47. Serial.print("Received Value: ");
  48. for (int i = 0; i < rxValue.length(); i++) {
  49. Serial.print(rxValue[i]);
  50. }
  51. Serial.println();
  52. // Do stuff based on the command received from the app
  53. if (rxValue.find("A") != -1) {
  54. Serial.print("Turning ON!");
  55. digitalWrite(LED, HIGH);
  56. }
  57. else if (rxValue.find("B") != -1) {
  58. Serial.print("Turning OFF!");
  59. digitalWrite(LED, LOW);
  60. }
  61. Serial.println();
  62. Serial.println("*********");
  63. }
  64. }
  65. };
  66. void setup() {
  67. Serial.begin(115200);
  68. pinMode(LED, OUTPUT);
  69. // Create the BLE Device
  70. BLEDevice::init("ESP32 UART Test"); // Give it a name
  71. // Create the BLE Server
  72. BLEServer *pServer = BLEDevice::createServer();
  73. pServer->setCallbacks(new MyServerCallbacks());
  74. // Create the BLE Service
  75. BLEService *pService = pServer->createService(SERVICE_UUID);
  76. // Create a BLE Characteristic
  77. pCharacteristic = pService->createCharacteristic(
  78. CHARACTERISTIC_UUID_TX,
  79. BLECharacteristic::PROPERTY_NOTIFY
  80. );
  81. pCharacteristic->addDescriptor(new BLE2902());
  82. BLECharacteristic *pCharacteristic = pService->createCharacteristic(
  83. CHARACTERISTIC_UUID_RX,
  84. BLECharacteristic::PROPERTY_WRITE
  85. );
  86. pCharacteristic->setCallbacks(new MyCallbacks());
  87. // Start the service
  88. pService->start();
  89. // Start advertising
  90. pServer->getAdvertising()->start();
  91. Serial.println("Waiting a client connection to notify...");
  92. }
  93. void loop() {
  94. if (deviceConnected) {
  95. // Fabricate some arbitrary junk for now...
  96. txValue = analogRead(readPin) / 3.456; // This could be an actual sensor reading!
  97. // Let's convert the value to a char array:
  98. char txString[8]; // make sure this is big enuffz
  99. dtostrf(txValue, 1, 2, txString); // float_val, min_width, digits_after_decimal, char_buffer
  100. // pCharacteristic->setValue(&txValue, 1); // To send the integer value
  101. // pCharacteristic->setValue("Hello!"); // Sending a test message
  102. pCharacteristic->setValue(txString);
  103. pCharacteristic->notify(); // Send the value to the app!
  104. Serial.print("*** Sent Value: ");
  105. Serial.print(txString);
  106. Serial.println(" ***");
  107. // You can add the rxValue checks down here instead
  108. // if you set "rxValue" as a global var at the top!
  109. // Note you will have to delete "std::string" declaration
  110. // of "rxValue" in the callback function.
  111. // if (rxValue.find("A") != -1) {
  112. // Serial.println("Turning ON!");
  113. // digitalWrite(LED, HIGH);
  114. // }
  115. // else if (rxValue.find("B") != -1) {
  116. // Serial.println("Turning OFF!");
  117. // digitalWrite(LED, LOW);
  118. // }
  119. }
  120. delay(1000);
  121. }

Step 3:下载安装 APP 测试工具

可以在资源栏下载:https://download.csdn.net/download/liwei16611/10526621

3、代码解释

3.1、库文件:

  1. #include <BLEDevice.h>
  2. #include <BLEServer.h>
  3. #include <BLEUtils.h>
  4. #include <BLE2902.h>

创建 BLE 设备:

BLEDevice::init("ESP32 UART Test"); // Give it a name

创建 BLE server:

  1. BLEServer *pServer = BLEDevice::createServer();
  2. pServer->setCallbacks(new MyServerCallbacks());

创建 BLE service:

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

添加 characteristics:

  1. pCharacteristic = pService->createCharacteristic(
  2. CHARACTERISTIC_UUID_TX,
  3. BLECharacteristic::PROPERTY_NOTIFY
  4. );
  5. pCharacteristic->addDescriptor(new BLE2902());
  6. BLECharacteristic *pCharacteristic = pService->createCharacteristic(
  7. CHARACTERISTIC_UUID_RX,
  8. BLECharacteristic::PROPERTY_WRITE
  9. );
  10. pCharacteristic->setCallbacks(new MyCallbacks());

启动广播:

  1. pServer->getAdvertising()->start();
  2. Serial.println("Waiting a client connection to notify...");

3.2、定义 service 和 characteristic UUID:TX | RX

#define SERVICE_UUID           "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
  1. #define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
  2. #define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

3.3、蓝牙连接回调函数

  1. class MyServerCallbacks: public BLEServerCallbacks {<br> void onConnect(BLEServer* pServer) {
  2. deviceConnected = true;
  3. };
  4. void onDisconnect(BLEServer* pServer) {
  5. deviceConnected = false;
  6. }
  7. };

3.4、数据接收回调函数

  1. class MyCallbacks: public BLECharacteristicCallbacks {<br> void onWrite(BLECharacteristic *pCharacteristic) {
  2. std::string rxValue = pCharacteristic->getValue();</p><p> if (rxValue.length() > 0) {
  3. Serial.println("*********");
  4. Serial.print("Received Value: ");</p><p> for (int i = 0; i < rxValue.length(); i++) {
  5. Serial.print(rxValue[i]);
  6. }</p><p> Serial.println();</p><p> // Do stuff based on the command received from the app
  7. if (rxValue.find("A") != -1) {
  8. Serial.print("Turning ON!");
  9. digitalWrite(LED, HIGH);
  10. }
  11. else if (rxValue.find("B") != -1) {
  12. Serial.print("Turning OFF!");
  13. digitalWrite(LED, LOW);
  14. }</p><p> Serial.println();
  15. Serial.println("*********");
  16. }
  17. }
  18. };

refer:

http://www.instructables.com/id/ESP32-BLE-Android-App-Arduino-IDE-AWESOME/

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/211560
推荐阅读
相关标签
  

闽ICP备14008679号