BLE code bootloop ESP32

this code bootloops unles i put delay(1); in the loop. Ive been looking for a solution for a while im not sure what else i can do.

Im using a ESP32 WROOM 32

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;

#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"         // Change this to your own service UUID
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"  // Change this to your own characteristic UUID

class MyServerCallbacks : public BLEServerCallbacks {
  void onConnect(BLEServer* pServer) {
    Serial.println("A device has connected");
  };

  void onDisconnect(BLEServer* pServer) {
    Serial.println("A device has disconnected");
    pServer->startAdvertising();  // Start advertising again to allow new connections
  }
};


void setup() {
  Serial.begin(115200);
  BLEDevice::init("ESP32_BLE_Server");
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());
  BLEService* pService = pServer->createService(SERVICE_UUID);
  pCharacteristic = pService->createCharacteristic(
    CHARACTERISTIC_UUID,
    BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE);
  pCharacteristic->addDescriptor(new BLE2902());
  pService->start();
  BLEAdvertising* pAdvertising = pServer->getAdvertising();
  pAdvertising->start();
}

void loop() {

}

what's the error message you see in the Serial monitor when the ESP32 reboots? did you try to explore what's the cause with GitHub - me-no-dev/EspExceptionDecoder: Exception Stack Trace Decoder for ESP8266 and ESP32

i did. it just kept taking back to different areas where mentioning freertos or ble gat services, i tried to narrow it down and made that small program. but i have a larger program ad i have weird memory problems. crashes at random times always related to the ble stuff

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
std::string ledPatternsData = "PATTERN NUMBER 1,ADC METER 1,ADC METER 2,ADC RED YELLOW GREEN*";  //* is ending car to receiver
BLECharacteristic *pCharacteristic;
BLEAdvertising *pAdvertising;
BLEServer *pServer;
std::string lastReceivedChunk;

int chunkIndex = 0;
bool sendingPattern = false;   // Declare sendingPattern
const int chunkDataSize = 13;  // 6 bytes for pattern data
const int chunkIndexSize = 4;  // 2 bytes for pattern index //nyte for delimiter
const int IDSize = 3;          // 3 bytes for ID //nyte for delimiter
//const int dataSize = 9;        // Example data size, including delimiter and colon
bool chunkReceived = false;
const int chunkSize = IDSize + chunkIndexSize;
unsigned long previousMillis = 0;
unsigned long retryMillis = 0;
unsigned long retryInterval = 100;
bool enableRetries = false;
int retryCounter = 0;
int retryLimit = 20;
bool verifyingPattern = false;  // Declare verifyingPattern within the class
////////////////////////////////////////////////


void initBLE() {
  BLEDevice::init("ESP32_DEV_1");
  BLEServer *pServer = BLEDevice::createServer();
  BLEService *pService = pServer->createService(BLEUUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b"));
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
    BLEUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8"),
    BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY | BLECharacteristic::PROPERTY_INDICATE);
  pServer->setCallbacks(new MyServerCallbacks());
  pCharacteristic->setCallbacks(new MyCallbacks());
  pCharacteristic->addDescriptor(new BLE2902());
  pService->start();
  BLEAdvertising *pAdvertising = pServer->getAdvertising();
  pAdvertising->start();
}

and the main

#include <FastLED.h>

#define potPin 32
#define LED_PIN_1 27
#define NUM_LEDS_STRIP_1 144
#define NUM_LEDS_STRIP_2 144
#define NUM_LEDS 144

CRGBArray<NUM_LEDS> leds;
int brightnessValue = 0;
int red = 0;
int green = 0;
int blue = 0;
int potVal = 0;
int trailLength = 0;
int readMode = 0;
int j = NUM_LEDS - 1;
const int numReadings = 20;
unsigned long readings[numReadings];  // the readings from the analog input
unsigned long readIndex = 0;          // the index of the current reading
unsigned long total = 0;              // the running total
int average = 0;
bool powerState = false;  // Global variable to store power state
unsigned long now = 0;

#include "BLE_CODE.h"

void setup() {
  Serial.begin(115200);
  FastLED.addLeds<WS2812, LED_PIN_1, GRB>(leds, NUM_LEDS_STRIP_1);
  //  FastLED.addLeds<WS2812, LED_PIN_2, GRB>(leds, NUM_LEDS_STRIP_2);
  initBLE();  // Call the function to initialize BLE
}

void loop() {
  //  delay(1);
  if (enableRetries) {
    if (retryCounter < retryLimit) {
      if (millis() - retryMillis >= retryInterval) {
        Serial.println("Retrying...");
        pCharacteristic->setValue(lastReceivedChunk);
        pCharacteristic->notify();
        retryMillis = millis();  // Reset the retry timer
        retryCounter++;          // Increment the retry counter
      }
    } else {
      Serial.println("Retry limit reached, Timed Out.");
      enableRetries = false;  // Disable retries
      retryCounter = 0;       // Reset retry counter
      sendingPattern = false;
      verifyingPattern = false;
    }
  } else {
  }

  if (millis() - now >= 750) {
    Serial.print("potVal:");
    Serial.println(potVal);
    Serial.print("Free Heap: ");
    Serial.println(ESP.getFreeHeap());

    now = millis();
  }

  total = total - readings[readIndex];
  readings[readIndex] = analogRead(potPin);
  total = total + readings[readIndex];
  readIndex = readIndex + 1;
  if (readIndex >= numReadings) {
    readIndex = 0;
  }
  average = total / numReadings;
  potVal = constrain(average, 200, 3070);  // This locks the min, max of the value.
  if (potVal < 2951) {                     // This check to see if the HIGH value is OUT OF BOUNDS.
    trailLength = map(potVal, 200, 2950, 0, (NUM_LEDS - 1));
  } else {                                                    //If it IS then we lock the value down to max on the map.
    potVal = 2950;                                            // here we lock it down.
    trailLength = map(potVal, 200, 2950, 0, (NUM_LEDS - 1));  // Then we run a standard map.
  }

}

the stack traces seemed to always just kept taking me in circles.

Im wondering if the issue coud be with my variant generic wroom 32.

Im using esp boards by espriff 2.0.11

looking at your initial code - for those 3 calls

can you check the returned value (does init work? is the pServer pointer non null ? do you get a non null pService pointer?)

when i run the code, with a delay(1); in the loop, it will advertise the ble and i can communicate over the characteristic, the sending chunk works.

But for example if i send id 777 and select pattern 3 it will only show 3 of my 144 leds, but if i just flash it with readMode set to 3 and dont use ble to sleect it, it works fine. but at random times it crashes. the behavior of the program is as if somthing is overflowing, but i watched the heap, seem to after BLE enable it still had 15k and 32 before ble

random crashes can be indeed linked to buffer overflows. Have you double checks all your leds[....] assignments to ensure the index is within 0 and NUM_LEDS-1?


why don't you do

  average = total / numReadings;
  potVal = constrain(average, 200, 2950);  // This locks the min, max of the value.
  trailLength = map(potVal, 200, 2950, 0, (NUM_LEDS - 1));

honestly ive been working on this ble issue so long now i cant remember i think i wanted to limit the end of the range differently.

I ordered some espressif verion of the esp modules. I havnt been able to find a direct overflow in my variables of led logic. but i may have missed something. I have other issues too with just the ble, like if i try to create a second characteristicit wont show up in my scans. , and when i do service discovery on the server it shows 5 of the same characteristic id.

Something is wrong but i havnt been able to pinpoint it. i went through ever issue on GitHub but nothing really directly related that i notice.

if you run code like the one in this tutorial ESP32 Bluetooth Low Energy (BLE) on Arduino IDE | Random Nerd Tutorials, does it work as expected ?

I just tried neopixel and im still getting weird issues, the strips patters seems to wrok okay but now it just crashes at rando still.

If i put this in my setup

fill_solid(leds, NUM_LEDS, CRGB(0, 0, 0));
            FastLED.show();

the i can switch readMode to 3 with the BLE and not have any strange issues with it, but it confuses me because when i sent a color wheel command thats what it does anyways,

without that in the setup i cannot switch readMode with the BLE without huge problems.

What about post 8

Ensuring your esp works with known code would be a first start

Neopixels and their demand on precise timing might create issues (eg it’s a mess with IR control). So try with no animation in your code

you were right the whole time. i had this global,

BLECharacteristic *pCharacteristic;  // had this globally defined 

but..... in init i had

BLECharacteristic *pCharacteristic = pService->createCharacteristic(
    BLEUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8"),
    BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY | BLECharacteristic::PROPERTY_INDICATE);

this overriding the global one i guess, it was returning null.

actually you were creating a local one and thus never setting up the global one.

sorry yea that's what i mean. it took me a couple of days to find that lol. but now everything seems to work pretty good thanks,

It never happened to me, never :innocent:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.