Reducing memory usage when using BLE

reza_neam
Posts: 12
Joined: Thu Dec 31, 2020 9:19 pm

Reducing memory usage when using BLE

Postby reza_neam » Fri Jan 01, 2021 10:03 am

I am trying to use BLE and WiFi in my project in Platform IO and I use Arduino as the development platform.
I quickly notice that BLE and WiFi are eating almost all the heap I have in ESP32.
I did a quick investigation to see how much heap they will take.

I found out in the code below BLE is taking about 175KB of the heap. Please note that I did add any services and characteristics.

Code: Select all

#include <Arduino.h>
#include <BLEDevice.h>

void setup()
{
  Serial.begin(115200);
  Serial.println("Free heap is " + String(ESP.getFreeHeap()));
  BLEDevice::init("deviceName");
  Serial.println("+BLE => Free heap is " + String(ESP.getFreeHeap()));
}

void loop()
{
}
It's almost the same thing with WiFi. Having ESP32 only connect to the WiFi takes about 100KB of the heap.
I am wondering is there any way to reduce/manage the size of the heap being used?

lbernstone
Posts: 828
Joined: Mon Jul 22, 2019 3:20 pm

Re: Reducing memory usage when using BLE

Postby lbernstone » Sat Jan 02, 2021 2:37 pm

The NimBLE library uses far less memory (and code space).
https://github.com/h2zero/NimBLE-Arduino

reza_neam
Posts: 12
Joined: Thu Dec 31, 2020 9:19 pm

Re: Reducing memory usage when using BLE

Postby reza_neam » Tue Jan 05, 2021 3:17 pm

Thank you. That helped a lot and save around 100kB of the heap :)

bobolink
Posts: 98
Joined: Mon Feb 26, 2018 4:17 pm

Re: Reducing memory usage when using BLE

Postby bobolink » Sat Jan 09, 2021 5:01 pm

Thanks. I completely missed NimBLE.
I saved about 6% program memory.

Using BlueDroid
Sketch uses 1095047 bytes (16%) of program storage space. Maximum is 6553600 bytes.
NimBLE
Sketch uses 656243 bytes (10%) of program storage space. Maximum is 6553600 bytes.

Notes:
If you are using the Arduino re-factored original example, you might add the code where the device is already known in connectToServer().
Also, I missed this in my original version:
/** Optional: set the transmit power, default is 3db */
NimBLEDevice::setPower(ESP_PWR_LVL_P9); /** +9db */

bobolink
Posts: 98
Joined: Mon Feb 26, 2018 4:17 pm

Re: Reducing memory usage when using BLE

Postby bobolink » Sat Jan 09, 2021 9:02 pm

Ooooops.
Some Callback processing causes a crash.
Stack size somewhere in Arduino version needs increasing I guess.
The troubleshooting costs might exceed the benefits.
:shock:

Who is online

Users browsing this forum: No registered users and 73 guests