Hi.
I have a Xiao ESP32S3 Sense. I am trying use BLE to execute code based on the value of a characteristic.
I find this to be very difficult, and I’m sure that’s because I’ve missed something simple. The server example works unmodified.
I add a global declaration of pCharacteristic so that I can refer to it in loop().
Then I add an if function to turn an LED on/off based on the characteristic. This is essentially pseudocode, it doesn’t work. I get string conversion errors. I’ve also tried simply printing the characteristic value to serial, but I can’t find a conversion that works.
Is there a simpler way to do something like this, or a string conversion to either string og int that works?
Here is the code:
#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"
BLECharacteristic* pCharacteristic = NULL;
void setup() {
pinMode(D2, OUTPUT);
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("0");
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() {
int value = pCharacteristic->getValue();
if (value == 1) { //if characteristic is 1, set lLED to on
digitalWrite(D2, HIGH);
} else {
digitalWrite(D2, LOW);
}
delay(2000);
}
And the error:
Compilation error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'int' in initialization