您现在的位置是:网站首页> 硬件

ESP32 低功耗蓝牙的例子代码

  • 硬件
  • 2021-09-30
  • 1068人已阅读
摘要

1.简单的server

/*

    Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp

    Ported to Arduino ESP32 by Evandro Copercini

    updates by chegewara

*/


#include <BLEDevice.h>

#include <BLEUtils.h>

#include <BLEServer.h>


// See the following for generating UUIDs:

// https://www.uuidgenerator.net/


#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"

#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"


void setup() {

  Serial.begin(115200);

  Serial.println("Starting BLE work!");


  BLEDevice::init("Long name works now");

  BLEServer *pServer = BLEDevice::createServer();

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

  BLECharacteristic *pCharacteristic = pService->createCharacteristic(

                                         CHARACTERISTIC_UUID,

                                         BLECharacteristic::PROPERTY_READ |

                                         BLECharacteristic::PROPERTY_WRITE

                                       );


  pCharacteristic->setValue("Hello World says Neil");

  pService->start();

  // BLEAdvertising *pAdvertising = pServer->getAdvertising();  // this still is working for backward compatibility

  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();

  pAdvertising->addServiceUUID(SERVICE_UUID);

  pAdvertising->setScanResponse(true);

  pAdvertising->setMinPreferred(0x06);  // functions that help with iPhone connections issue

  pAdvertising->setMinPreferred(0x12);

  BLEDevice::startAdvertising();

  Serial.println("Characteristic defined! Now you can read it in your phone!");

}


void loop() {

  // put your main code here, to run repeatedly:

  delay(2000);

}

2.简单的client

/**

 * A BLE client example that is rich in capabilities.

 * There is a lot new capabilities implemented.

 * author unknown

 * updated by chegewara

 */


#include "BLEDevice.h"

//#include "BLEScan.h"


// The remote service we wish to connect to.

static BLEUUID serviceUUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");

// The characteristic of the remote service we are interested in.

static BLEUUID    charUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");


static boolean doConnect = false;

static boolean connected = false;

static boolean doScan = false;

static BLERemoteCharacteristic* pRemoteCharacteristic;

static BLEAdvertisedDevice* myDevice;


static void notifyCallback(

  BLERemoteCharacteristic* pBLERemoteCharacteristic,

  uint8_t* pData,

  size_t length,

  bool isNotify) {

    Serial.print("Notify callback for characteristic ");

    Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());

    Serial.print(" of data length ");

    Serial.println(length);

    Serial.print("data: ");

    Serial.println((char*)pData);

}


class MyClientCallback : public BLEClientCallbacks {

  void onConnect(BLEClient* pclient) {

  }


  void onDisconnect(BLEClient* pclient) {

    connected = false;

    Serial.println("onDisconnect");

  }

};


bool connectToServer() {

    Serial.print("Forming a connection to ");

    Serial.println(myDevice->getAddress().toString().c_str());

    

    BLEClient*  pClient  = BLEDevice::createClient();

    Serial.println(" - Created client");


    pClient->setClientCallbacks(new MyClientCallback());


    // Connect to the remove BLE Server.

    pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)

    Serial.println(" - Connected to server");


    // Obtain a reference to the service we are after in the remote BLE server.

    BLERemoteService* pRemoteService = pClient->getService(serviceUUID);

    if (pRemoteService == nullptr) {

      Serial.print("Failed to find our service UUID: ");

      Serial.println(serviceUUID.toString().c_str());

      pClient->disconnect();

      return false;

    }

    Serial.println(" - Found our service");



    // Obtain a reference to the characteristic in the service of the remote BLE server.

    pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);

    if (pRemoteCharacteristic == nullptr) {

      Serial.print("Failed to find our characteristic UUID: ");

      Serial.println(charUUID.toString().c_str());

      pClient->disconnect();

      return false;

    }

    Serial.println(" - Found our characteristic");


    // Read the value of the characteristic.

    if(pRemoteCharacteristic->canRead()) {

      std::string value = pRemoteCharacteristic->readValue();

      Serial.print("The characteristic value was: ");

      Serial.println(value.c_str());

    }


    if(pRemoteCharacteristic->canNotify())

      pRemoteCharacteristic->registerForNotify(notifyCallback);


    connected = true;

    return true;

}

/**

 * Scan for BLE servers and find the first one that advertises the service we are looking for.

 */

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {

 /**

   * Called for each advertising BLE server.

   */

  void onResult(BLEAdvertisedDevice advertisedDevice) {

    Serial.print("BLE Advertised Device found: ");

    Serial.println(advertisedDevice.toString().c_str());


    // We have found a device, let us now see if it contains the service we are looking for.

    if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {


      BLEDevice::getScan()->stop();

      myDevice = new BLEAdvertisedDevice(advertisedDevice);

      doConnect = true;

      doScan = true;


    } // Found our server

  } // onResult

}; // MyAdvertisedDeviceCallbacks



void setup() {

  Serial.begin(115200);

  Serial.println("Starting Arduino BLE Client application...");

  BLEDevice::init("");


  // Retrieve a Scanner and set the callback we want to use to be informed when we

  // have detected a new device.  Specify that we want active scanning and start the

  // scan to run for 5 seconds.

  BLEScan* pBLEScan = BLEDevice::getScan();

  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());

  pBLEScan->setInterval(1349);

  pBLEScan->setWindow(449);

  pBLEScan->setActiveScan(true);

  pBLEScan->start(5, false);

} // End of setup.



// This is the Arduino main loop function.

void loop() {


  // If the flag "doConnect" is true then we have scanned for and found the desired

  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are 

  // connected we set the connected flag to be true.

  if (doConnect == true) {

    if (connectToServer()) {

      Serial.println("We are now connected to the BLE Server.");

    } else {

      Serial.println("We have failed to connect to the server; there is nothin more we will do.");

    }

    doConnect = false;

  }


  // If we are connected to a peer BLE Server, update the characteristic each time we are reached

  // with the current time since boot.

  if (connected) {

    String newValue = "Time since boot: " + String(millis()/1000);

    Serial.println("Setting new characteristic value to \"" + newValue + "\"");

    

    // Set the characteristic's value to be the array of bytes that is actually a string.

    pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());

  }else if(doScan){

    BLEDevice::getScan()->start(0);  // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino

  }

  

  delay(1000); // Delay a second between loops.

} // End of loop

3.低功耗蓝牙IBeacon

/*

   Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp

   Ported to Arduino ESP32 by pcbreflux

*/


 

/*

   Create a BLE server that will send periodic iBeacon frames.

   The design of creating the BLE server is:

   1. Create a BLE Server

   2. Create advertising data

   3. Start advertising.

   4. wait

   5. Stop advertising.

   6. deep sleep

   

*/

#include "sys/time.h"


#include "BLEDevice.h"

#include "BLEUtils.h"

#include "BLEBeacon.h"

#include "esp_sleep.h"


#define GPIO_DEEP_SLEEP_DURATION     10  // sleep x seconds and then wake up

RTC_DATA_ATTR static time_t last;        // remember last boot in RTC Memory

RTC_DATA_ATTR static uint32_t bootcount; // remember number of boots in RTC Memory


#ifdef __cplusplus

extern "C" {

#endif


uint8_t temprature_sens_read();

//uint8_t g_phyFuns;


#ifdef __cplusplus

}

#endif


// See the following for generating UUIDs:

// https://www.uuidgenerator.net/

BLEAdvertising *pAdvertising;

struct timeval now;


#define BEACON_UUID           "8ec76ea3-6668-48da-9866-75be8bc86f4d" // UUID 1 128-Bit (may use linux tool uuidgen or random numbers via https://www.uuidgenerator.net/)


void setBeacon() {


  BLEBeacon oBeacon = BLEBeacon();

  oBeacon.setManufacturerId(0x4C00); // fake Apple 0x004C LSB (ENDIAN_CHANGE_U16!)

  oBeacon.setProximityUUID(BLEUUID(BEACON_UUID));

  oBeacon.setMajor((bootcount & 0xFFFF0000) >> 16);

  oBeacon.setMinor(bootcount&0xFFFF);

  BLEAdvertisementData oAdvertisementData = BLEAdvertisementData();

  BLEAdvertisementData oScanResponseData = BLEAdvertisementData();

  

  oAdvertisementData.setFlags(0x04); // BR_EDR_NOT_SUPPORTED 0x04

  

  std::string strServiceData = "";

  

  strServiceData += (char)26;     // Len

  strServiceData += (char)0xFF;   // Type

  strServiceData += oBeacon.getData(); 

  oAdvertisementData.addData(strServiceData);

  

  pAdvertising->setAdvertisementData(oAdvertisementData);

  pAdvertising->setScanResponseData(oScanResponseData);


}


void setup() {


    

  Serial.begin(115200);

  gettimeofday(&now, NULL);


  Serial.printf("start ESP32 %d\n",bootcount++);


  Serial.printf("deep sleep (%lds since last reset, %lds since last boot)\n",now.tv_sec,now.tv_sec-last);


  last = now.tv_sec;

  

  // Create the BLE Device

  BLEDevice::init("");


  // Create the BLE Server

  // BLEServer *pServer = BLEDevice::createServer(); // <-- no longer required to instantiate BLEServer, less flash and ram usage


  pAdvertising = BLEDevice::getAdvertising();

  

  setBeacon();

   // Start advertising

  pAdvertising->start();

  Serial.println("Advertizing started...");

  delay(100);

  pAdvertising->stop();

  Serial.printf("enter deep sleep\n");

  esp_deep_sleep(1000000LL * GPIO_DEEP_SLEEP_DURATION);

  Serial.printf("in deep sleep\n");

}


void loop() {

}

4.BLE_nodtify

/*

    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

    updated by chegewara


   Create a BLE server that, once we receive a connection, will send periodic notifications.

   The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b

   And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8


   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.


   A connect hander associated with the server starts a background task that performs notification

   every couple of seconds.

*/

#include <BLEDevice.h>

#include <BLEServer.h>

#include <BLEUtils.h>

#include <BLE2902.h>


BLEServer* pServer = NULL;

BLECharacteristic* pCharacteristic = NULL;

bool deviceConnected = false;

bool oldDeviceConnected = false;

uint32_t value = 0;


// See the following for generating UUIDs:

// https://www.uuidgenerator.net/


#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"

#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"



class MyServerCallbacks: public BLEServerCallbacks {

    void onConnect(BLEServer* pServer) {

      deviceConnected = true;

    };


    void onDisconnect(BLEServer* pServer) {

      deviceConnected = false;

    }

};




void setup() {

  Serial.begin(115200);


  // Create the BLE Device

  BLEDevice::init("ESP32");


  // Create the BLE Server

  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,

                      BLECharacteristic::PROPERTY_READ   |

                      BLECharacteristic::PROPERTY_WRITE  |

                      BLECharacteristic::PROPERTY_NOTIFY |

                      BLECharacteristic::PROPERTY_INDICATE

                    );


  // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml

  // Create a BLE Descriptor

  pCharacteristic->addDescriptor(new BLE2902());


  // Start the service

  pService->start();


  // Start advertising

  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();

  pAdvertising->addServiceUUID(SERVICE_UUID);

  pAdvertising->setScanResponse(false);

  pAdvertising->setMinPreferred(0x0);  // set value to 0x00 to not advertise this parameter

  BLEDevice::startAdvertising();

  Serial.println("Waiting a client connection to notify...");

}


void loop() {

    // notify changed value

    if (deviceConnected) {

        pCharacteristic->setValue((uint8_t*)&value, 4);

        pCharacteristic->notify();

        value++;

        delay(3); // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms

    }

    // disconnecting

    if (!deviceConnected && oldDeviceConnected) {

        delay(500); // give the bluetooth stack the chance to get things ready

        pServer->startAdvertising(); // restart advertising

        Serial.println("start advertising");

        oldDeviceConnected = deviceConnected;

    }

    // connecting

    if (deviceConnected && !oldDeviceConnected) {

        // do stuff here on connecting

        oldDeviceConnected = deviceConnected;

    }

}

5.BLE_scan

/*

   Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp

   Ported to Arduino ESP32 by Evandro Copercini

*/


#include <BLEDevice.h>

#include <BLEUtils.h>

#include <BLEScan.h>

#include <BLEAdvertisedDevice.h>


int scanTime = 5; //In seconds

BLEScan* pBLEScan;


class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {

    void onResult(BLEAdvertisedDevice advertisedDevice) {

      Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());

    }

};


void setup() {

  Serial.begin(115200);

  Serial.println("Scanning...");


  BLEDevice::init("");

  pBLEScan = BLEDevice::getScan(); //create new scan

  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());

  pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster

  pBLEScan->setInterval(100);

  pBLEScan->setWindow(99);  // less or equal setInterval value

}


void loop() {

  // put your main code here, to run repeatedly:

  BLEScanResults foundDevices = pBLEScan->start(scanTime, false);

  Serial.print("Devices found: ");

  Serial.println(foundDevices.getCount());

  Serial.println("Scan done!");

  pBLEScan->clearResults();   // delete results fromBLEScan buffer to release memory

  delay(2000);

}

6.BLE_server_multiconnect


/*

    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

    updated by chegewara


   Create a BLE server that, once we receive a connection, will send periodic notifications.

   The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b

   And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8


   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.


   A connect hander associated with the server starts a background task that performs notification

   every couple of seconds.

*/

#include <BLEDevice.h>

#include <BLEServer.h>

#include <BLEUtils.h>

#include <BLE2902.h>


BLEServer* pServer = NULL;

BLECharacteristic* pCharacteristic = NULL;

bool deviceConnected = false;

bool oldDeviceConnected = false;

uint32_t value = 0;


// See the following for generating UUIDs:

// https://www.uuidgenerator.net/


#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"

#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"



class MyServerCallbacks: public BLEServerCallbacks {

    void onConnect(BLEServer* pServer) {

      deviceConnected = true;

      BLEDevice::startAdvertising();

    };


    void onDisconnect(BLEServer* pServer) {

      deviceConnected = false;

    }

};




void setup() {

  Serial.begin(115200);


  // Create the BLE Device

  BLEDevice::init("ESP32");


  // Create the BLE Server

  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,

                      BLECharacteristic::PROPERTY_READ   |

                      BLECharacteristic::PROPERTY_WRITE  |

                      BLECharacteristic::PROPERTY_NOTIFY |

                      BLECharacteristic::PROPERTY_INDICATE

                    );


  // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml

  // Create a BLE Descriptor

  pCharacteristic->addDescriptor(new BLE2902());


  // Start the service

  pService->start();


  // Start advertising

  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();

  pAdvertising->addServiceUUID(SERVICE_UUID);

  pAdvertising->setScanResponse(false);

  pAdvertising->setMinPreferred(0x0);  // set value to 0x00 to not advertise this parameter

  BLEDevice::startAdvertising();

  Serial.println("Waiting a client connection to notify...");

}


void loop() {

    // notify changed value

    if (deviceConnected) {

        pCharacteristic->setValue((uint8_t*)&value, 4);

        pCharacteristic->notify();

        value++;

        delay(10); // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms

    }

    // disconnecting

    if (!deviceConnected && oldDeviceConnected) {

        delay(500); // give the bluetooth stack the chance to get things ready

        pServer->startAdvertising(); // restart advertising

        Serial.println("start advertising");

        oldDeviceConnected = deviceConnected;

    }

    // connecting

    if (deviceConnected && !oldDeviceConnected) {

        // do stuff here on connecting

        oldDeviceConnected = deviceConnected;

    }

}

7.BLE_uart

/*

    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>


BLEServer *pServer = NULL;

BLECharacteristic * pTxCharacteristic;

bool deviceConnected = false;

bool oldDeviceConnected = false;

uint8_t txValue = 0;


// 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();

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

      }

    }

};



void setup() {

  Serial.begin(115200);


  // Create the BLE Device

  BLEDevice::init("UART Service");


  // Create the BLE Server

  pServer = BLEDevice::createServer();

  pServer->setCallbacks(new MyServerCallbacks());


  // Create the BLE Service

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


  // Create a BLE Characteristic

  pTxCharacteristic = pService->createCharacteristic(

CHARACTERISTIC_UUID_TX,

BLECharacteristic::PROPERTY_NOTIFY

);

                      

  pTxCharacteristic->addDescriptor(new BLE2902());


  BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(

CHARACTERISTIC_UUID_RX,

BLECharacteristic::PROPERTY_WRITE

);


  pRxCharacteristic->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) {

        pTxCharacteristic->setValue(&txValue, 1);

        pTxCharacteristic->notify();

        txValue++;

delay(10); // bluetooth stack will go into congestion, if too many packets are sent

}


    // disconnecting

    if (!deviceConnected && oldDeviceConnected) {

        delay(500); // give the bluetooth stack the chance to get things ready

        pServer->startAdvertising(); // restart advertising

        Serial.println("start advertising");

        oldDeviceConnected = deviceConnected;

    }

    // connecting

    if (deviceConnected && !oldDeviceConnected) {

// do stuff here on connecting

        oldDeviceConnected = deviceConnected;

    }

}

8.BLE_write

/*

    Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleWrite.cpp

    Ported to Arduino ESP32 by Evandro Copercini

*/


#include <BLEDevice.h>

#include <BLEUtils.h>

#include <BLEServer.h>


// See the following for generating UUIDs:

// https://www.uuidgenerator.net/


#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"

#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"



class MyCallbacks: public BLECharacteristicCallbacks {

    void onWrite(BLECharacteristic *pCharacteristic) {

      std::string value = pCharacteristic->getValue();


      if (value.length() > 0) {

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

        Serial.print("New value: ");

        for (int i = 0; i < value.length(); i++)

          Serial.print(value[i]);


        Serial.println();

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

      }

    }

};


void setup() {

  Serial.begin(115200);


  Serial.println("1- Download and install an BLE scanner app in your phone");

  Serial.println("2- Scan for BLE devices in the app");

  Serial.println("3- Connect to MyESP32");

  Serial.println("4- Go to CUSTOM CHARACTERISTIC in CUSTOM SERVICE and write something");

  Serial.println("5- See the magic =)");


  BLEDevice::init("MyESP32");

  BLEServer *pServer = BLEDevice::createServer();


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


  BLECharacteristic *pCharacteristic = pService->createCharacteristic(

                                         CHARACTERISTIC_UUID,

                                         BLECharacteristic::PROPERTY_READ |

                                         BLECharacteristic::PROPERTY_WRITE

                                       );


  pCharacteristic->setCallbacks(new MyCallbacks());


  pCharacteristic->setValue("Hello World");

  pService->start();


  BLEAdvertising *pAdvertising = pServer->getAdvertising();

  pAdvertising->start();

}


void loop() {

  // put your main code here, to run repeatedly:

  delay(2000);

}





上一篇:物联网硬件公司

下一篇:IO扩展模块

Top