Hi.
I've this piece of code that reads value from a BLE service CHARACTERISTIC_UUID (trasmitted from a BLE server to a BLE client, both running on two ESP32 boards) and write it on serial monitor:
#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("*********");
}
If I look at the serial monitor I see , depending on the value trasmitted form the BLE client device, two ASCII character : null and what it represents the 1 (ON) value.
The question is:
how should I modify the code so that I may have in the serial monitor not the ASCII value but the binary (or decimal) value and can I treat it as such and use in the rest of the code (i.e. : in an if ... than statement)?
Any idea?
Thanks in advance.
Read each character into an array of chars as you receive it which, because of the null termination, will turn it into a C style string (lowercase s) that you can convert to a decimal value using the atoi() function for use in later comparisons or calculations
Far from a complete example but it will show the principle that I was suggesting
byte charIndex = 0; //index to the array
char buffer[10]; //buffer for characters read
bool inputComplete = false; //flag to indicate that input is complete
void setup()
{
Serial.begin(115200);
}
void loop()
{
while (Serial.available()) //read characters if available
{
char inChar = Serial.read(); //read a character
buffer[charIndex++] = inChar; //put it in the buffer
if (inChar == '\0') //if end of input
{
inputComplete = true; //flag complete
break; //exit the while loop
}
}
if (inputComplete) //if input is complete
{
int theNumber = atoi(buffer); //convert string to integer
charIndex = 0; //reset the array index
//do whatever you need with theNumber value here
inputComplete = false; //ready for the next one
}
}