ESP32: Sending bluetooth data outside 'main loop'


Recently i have bought an ESP32 development board with the aim of using the bluetooth capability.
So far the board is great and it is possible for me to send and receive data over a bluetooth connection with my android Phone. The app on the Phone is home made using app inventor in combination with the ESP32 BLE_UART.ino example.

However, now I have a programming problem and for about 10 days I cannot find a solution. Can you please help me?

The problem is this:
I changed the ESP32 BLE_UART.ino example to do the following:
If the ESP32 receives a command (byte = 49) from my phone, I want to send data (byte) back from ESP32 to android Phone. This works, exept when I try to send data using a "pCharacteristic->notify();" line within the "onWrite(BLECharacteristic *pCharacteristic)"

However, if I do that, the ESP32 hangs. It strangely does not hang within the function itself, but on the next "pCharacteristic->notify();" call.

Sending data only works if that happens in the 'main' loop function. However, I don't want it to be send in the main loop, because it can then scramble variables in the rest of the program.

Below here you see the function which creates my problem. Can Anybody see what I am doing wrong?
Just to be clear: I don't have other errors and it is possible for me to send and receive data if sending is done in the 'main' loop.

Thank you for any help to get me going.
Kind regards,

The board I use is the WEMOS ESP32 with battery

class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();

      if (rxValue[0] == 49) {
        Serial.printf("do something: %d\n", testvalue);

        pCharacteristic->setValue(&testvalue, 1);
        pCharacteristic->notify(); //If I delete this line, the ESP32 keeps on working. However, it dows not send any data.
      Serial.printf("lengte na  : %d\n", rxValue.length());


You have not provided any links to any libraries, so we can only assume that pCharacteristic->notify() is not the correct method to be calling.

Hello PaulS,

Thank you very much for your reaction.
I have used the espressif library which can be found here: arduino-esp32/libraries at master · espressif/arduino-esp32 · GitHub

I know for sure that the pCharacteristic->notify() is correct, since it works in the ‘main’ loop function.
Do you have any idea why it does not work outside that main loop?

with kind regards,


testvalue is not defined anywhere in that snippet. It's hard to say why a snippet does not work, without context.