【IoT】Arduino 实现 ESP32 BLE 与 Android 手机的数据交互

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 编写实例:

/*
    Video: https://www.youtube.com/watch?v=oCMOYS71NIU
    Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp
    Ported to Arduino ESP32 by Evandro Copercini

   Create a BLE server that, once we receive a connection, will send periodic notifications.
   The service advertises itself as: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E
   Has a characteristic of: 6E400002-B5A3-F393-E0A9-E50E24DCCA9E - used for receiving data with "WRITE" 
   Has a characteristic of: 6E400003-B5A3-F393-E0A9-E50E24DCCA9E - used to send data with  "NOTIFY"

   The design of creating the BLE server is:
   1. Create a BLE Server
   2. Create a BLE Service
   3. Create a BLE Characteristic on the Service
   4. Create a BLE Descriptor on the characteristic
   5. Start the service.
   6. Start advertising.

   In this example rxValue is the data received (only accessible inside that function).
   And txValue is the data to be sent, in this example just a byte incremented every second. 
*/
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

BLECharacteristic *pCharacteristic;
bool deviceConnected = false;
float txValue = 0;
const int readPin = 32; // Use GPIO number. See ESP32 board pinouts
const int LED = 2; // Could be different depending on the dev board. I used the DOIT ESP32 dev board.

//std::string rxValue; // Could also make this a global var to access it in loop()

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

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

class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};

class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();

      if (rxValue.length() > 0) {
        Serial.println("*********");
        Serial.print("Received Value: ");

        for (int i = 0; i < rxValue.length(); i++) {
          Serial.print(rxValue[i]);
        }

        Serial.println();

        // Do stuff based on the command received from the app
        if (rxValue.find("A") != -1) { 
          Serial.print("Turning ON!");
          digitalWrite(LED, HIGH);
        }
        else if (rxValue.find("B") != -1) {
          Serial.print("Turning OFF!");
          digitalWrite(LED, LOW);
        }

        Serial.println();
        Serial.println("*********");
      }
    }
};

void setup() {
  Serial.begin(115200);

  pinMode(LED, OUTPUT);

  // Create the BLE Device
  BLEDevice::init("ESP32 UART Test"); // Give it a name

  // Create the BLE Server
  BLEServer *pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Create a BLE Characteristic
  pCharacteristic = pService->createCharacteristic(
                      CHARACTERISTIC_UUID_TX,
                      BLECharacteristic::PROPERTY_NOTIFY
                    );
                      
  pCharacteristic->addDescriptor(new BLE2902());

  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID_RX,
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setCallbacks(new MyCallbacks());

  // Start the service
  pService->start();

  // Start advertising
  pServer->getAdvertising()->start();
  Serial.println("Waiting a client connection to notify...");
}

void loop() {
  if (deviceConnected) {
    // Fabricate some arbitrary junk for now...
    txValue = analogRead(readPin) / 3.456; // This could be an actual sensor reading!

    // Let's convert the value to a char array:
    char txString[8]; // make sure this is big enuffz
    dtostrf(txValue, 1, 2, txString); // float_val, min_width, digits_after_decimal, char_buffer
    
//    pCharacteristic->setValue(&txValue, 1); // To send the integer value
//    pCharacteristic->setValue("Hello!"); // Sending a test message
    pCharacteristic->setValue(txString);
    
    pCharacteristic->notify(); // Send the value to the app!
    Serial.print("*** Sent Value: ");
    Serial.print(txString);
    Serial.println(" ***");

    // You can add the rxValue checks down here instead
    // if you set "rxValue" as a global var at the top!
    // Note you will have to delete "std::string" declaration
    // of "rxValue" in the callback function.
//    if (rxValue.find("A") != -1) { 
//      Serial.println("Turning ON!");
//      digitalWrite(LED, HIGH);
//    }
//    else if (rxValue.find("B") != -1) {
//      Serial.println("Turning OFF!");
//      digitalWrite(LED, LOW);
//    }
  }
  delay(1000);
}

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

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

3、代码解释

3.1、库文件:

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

创建 BLE 设备:

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

创建 BLE server:

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

创建 BLE service:

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

添加 characteristics:

pCharacteristic = pService->createCharacteristic(
                    CHARACTERISTIC_UUID_TX,
                    BLECharacteristic::PROPERTY_NOTIFY
                  );
pCharacteristic->addDescriptor(new BLE2902());
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                       CHARACTERISTIC_UUID_RX,
                                       BLECharacteristic::PROPERTY_WRITE
                                     );
pCharacteristic->setCallbacks(new MyCallbacks());

启动广播:

pServer->getAdvertising()->start();
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
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

3.3、蓝牙连接回调函数

class MyServerCallbacks: public BLEServerCallbacks {<br>    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };
    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};

3.4、数据接收回调函数

class MyCallbacks: public BLECharacteristicCallbacks {<br>    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();</p><p>      if (rxValue.length() > 0) {
        Serial.println("*********");
        Serial.print("Received Value: ");</p><p>        for (int i = 0; i < rxValue.length(); i++) {
          Serial.print(rxValue[i]);
        }</p><p>        Serial.println();</p><p>        // Do stuff based on the command received from the app
        if (rxValue.find("A") != -1) { 
          Serial.print("Turning ON!");
          digitalWrite(LED, HIGH);
        }
        else if (rxValue.find("B") != -1) {
          Serial.print("Turning OFF!");
          digitalWrite(LED, LOW);
        }</p><p>        Serial.println();
        Serial.println("*********");
      }
    }
};

refer:

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

### 回答1: Arduino是一种开源的硬件平台,可用于制作各种物联网设备和交互式项目。它基于单片机,并配备了方便易用的开发环境和编程语言。而ESP32是一种微控制器芯片,是Arduino的一种变种,具有强大的处理能力和丰富的连接选项,适用于更复杂的项目。 Golang是一种开源的编程语言,其特点是简洁、高效、高并发和静态类型。它适用于构建各种类型的应用程序,包括后端服务、网络应用和系统软件等。 结合ArduinoESP32,我们可以使用Golang作为主要的后端开发语言来与物联网设备进行通信和交互。由于Golang的高并发性能和简洁的语法,我们可以轻松地编写并管理与ArduinoESP32的通信,包括数据传输、传感器读取和控制指令。 使用Golang作为后端语言,我们可以快速构建各种物联网项目,如智能家居系统、智能农业设备、远程监控系统等。通过与ArduinoESP32的结合,我们可以轻松地控制和监控各种传感器和执行器,实现自动化和远程控制。 此外,借助Golang的丰富软件生态系统,我们可以轻松地扩展和集成其他第三方库和服务,从而为我们的物联网项目提供更多功能和选项。这使得我们能够更好地满足用户需求,并提供更好的用户体验。 总之,通过结合ArduinoESP32和Golang,我们可以构建功能强大、高效稳定的物联网设备和应用程序,实现更智能化和便捷的生活和工作体验。 ### 回答2: Arduino是一种开源电子平台,用于创建各种物联网IoT)项目。它是一种基于开放式硬件和软件的平台,提供了一个简单易用的方式来编程并与外部设备进行交互Arduino能够通过连接传感器、执行代码逻辑和输出控制信号来实现各种功能。 ESP32是一款流行的开发板,其主要特点是具有双核处理器和WiFi/蓝牙功能。它基于摩尔根智嵌入式平台,提供了丰富的功能和灵活性。ESP32适用于各种应用,包括物联网设备、嵌入式系统和智能家居等。 Golang(也称为Go)是一种现代化的编程语言,由Google开发。它具有简洁的语法、高效的并发性和良好的可读性。Golang特别适合开发高性能、可扩展的网络应用程序和后端系统。该语言是静态类型的,并提供了丰富的标准库,使编程更加简单和高效。 如果将这三者结合起来使用,可以实现强大的物联网应用。通过ArduinoESP32的组合,可以轻松连接和控制各种传感器和执行器。而使用Golang编程语言,可以开发出高效的后端系统,与ArduinoESP32进行通信和数据交换。这样,我们可以轻松地构建一个完整的物联网解决方案,实现从传感器到云平台的全程控制和监控。 总之,结合ArduinoESP32和Golang可以创建强大、高效的物联网应用。这个组合提供了开发和控制物联网设备所需的硬件和软件功能,并具有良好的扩展性和灵活性。无论是初学者还是专业开发人员都可以使用这些工具来创造出具有创新性和实用性的物联网解决方案。 ### 回答3: Arduino是一种开源电子平台,主要用于快速制作原型和开发各种电子设备。它有一个简单易用的编程环境,可通过简单的代码实现各种功能。ESP32是一种基于Arduino平台的开发板,具有WiFi和蓝牙功能,使其适用于物联网应用。它具有更强大的处理能力和更多的IO口,可用于连接各种传感器和执行器。 Golang是一种开源的编程语言,由Google开发。它具有强大的并发特性和内置的网络支持,非常适合构建高性能和可扩展的应用程序。Golang也可以与ArduinoESP32进行交互。 通过在ESP32上运行Golang程序,我们可以利用Golang的高效和并发处理能力来控制和监控与Arduino和各种传感器连接设备。Golang可以通过ESP32板上的WiFi和蓝牙功能与其他设备进行通信,比如通过WiFi连接到互联网或与其他智能设备进行数据交换。 使用Golang开发应用程序时,我们可以充分利用其丰富的标准库和第三方包,简化开发流程。Golang的简洁的语法和强大的错误处理机制也使得程序开发更加高效和易于维护。 总之,将ArduinoESP32和Golang结合使用可以实现更多复杂的功能和应用,扩展了Arduino平台的能力,并为开发者提供了更多灵活和高效的编程工具。这种组合不仅可以用于物联网应用,还可以应用于机器人控制、智能家居、自动化系统等领域。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

产品人卫朋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值