/* This ESP32 sketch works with MIT app ESP32_BLE_UART_LED It has 2 LEDs controlled by two buttons. inData is now being sent to App. It is based on the BLE_test.ino. 12/10/2019 */ #include #include #include #include #define RELAY_PIN_LED1 14 #define RELAY_PIN_LED2 15 BLECharacteristic *pCharacteristic; bool deviceConnected = false; uint8_t txValue = 0, state_LED1 = 0, state_LED2 = 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 Serial.println(">>>>>>>>>>>>>>>>>>>>>>>>"); //Test what came down... Serial.println(filterString.substring(0)); if(filterString.substring(0,1) == "t") { // Check for header if(filterString.substring(2) == "0") { state_LED1 = 1; Serial.println(state_LED1); } else { state_LED1 = 0; Serial.println(state_LED1); } } else if(filterString.substring(0,1) == "L") { // Check for header if(filterString.substring(2) == "0") { state_LED2 = 1; Serial.println(state_LED2); } else { state_LED2 = 0; Serial.println(state_LED2); } } } }; void setup() { Serial.begin(115200); pinMode(RELAY_PIN_LED1, OUTPUT); pinMode(RELAY_PIN_LED2, OUTPUT); // Create the BLE Device BLEDevice::init("BLE 2 LEDs, TX/RX"); // 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_LED1, state_LED1); digitalWrite(RELAY_PIN_LED2, state_LED2); String datastring = "ESP32: "; datastring += txValue; Serial.printf("*** Sent Value: %d ***\n", txValue); pCharacteristic->setValue(datastring.c_str()); pCharacteristic->notify(); txValue++; } delay(1000); }