Bluetooth Low Energy also referred to as Bluetooth LE is a new communication protocol similar to Bluetooth except that it is designed to consume less power while maintaining comparable functionality. For this reason, Bluetooth LE is the preferred choice of communication with IoT devices that have limited power resources.
In this project, we will be using IoT node along with the Analog board to demonstrate the application of BLE in ESP32. For this project we will be creating an android application using Thunkable online app builder and using that app we will be controlling the relay and also a simple message can be sent to the ESP32 from app to display it in the serial monitor.
To set up an Android app we will use an app building tool named as Thunkable. You can also use Thunkable and build your own Android app for this project. These are the steps to set up an Android app
#include <BLEDevice.h> #include <BLEServer.h> #include <BLEUtils.h> #include <BLE2902.h> #define RELAY_PIN 35 BLECharacteristic *pCharacteristic; bool deviceConnected = false; uint8_t txValue = 0, state = 0; String filterString; // 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(); filterString = rxValue.c_str(); // Convert to standard c string format if(filterString.substring(0,1) == "t") { // Check for header if(filterString.substring(2) == "0") { state = 1; } else { state = 0; } } } }; void setup() { Serial.begin(115200); pinMode(RELAY_PIN, OUTPUT); // Create the BLE Device BLEDevice::init("BLE Example"); // 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) { digitalWrite(RELAY_PIN, state); } }