Created
December 9, 2024 11:04
-
-
Save chiyanun/ca812d25624f90fcd16b8b24b65cd7bb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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> | |
#include <Base64.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" | |
#define led 32 | |
class MyCallbacks : public BLECharacteristicCallbacks { | |
void onWrite(BLECharacteristic *pCharacteristic) { | |
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("*********"); | |
Serial.println(value); | |
if (value == "on") { | |
digitalWrite(led, HIGH); | |
} else if (value == "off") { | |
digitalWrite(led, LOW); | |
}else if (value =="req_cert") { | |
Serial.println("Sending 'new-string-value' to connected device..."); | |
pCharacteristic->setValue("new-string-value"); | |
pCharacteristic->notify(); | |
} | |
} | |
} | |
}; | |
void setup() { | |
Serial.begin(115200); | |
pinMode(led, OUTPUT); | |
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 |BLECharacteristic::PROPERTY_NOTIFY); | |
pCharacteristic->setCallbacks(new MyCallbacks()); | |
pCharacteristic->setValue("Hello World"); | |
pService->start(); | |
BLEAdvertising *pAdvertising = pServer->getAdvertising(); | |
pAdvertising->start(); | |
BLEDevice::setMTU(512); | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
delay(2000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment