1

i have NodeMCU with es8266 onboard on it. I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen. So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

2

I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen.

Indeed they do. And such things can be a pain to track down.

So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

No, you can't. The "free" amount of heap does not equate to the top address of heap. Heap can (and generally does) have holes in it. The "free" space is the sum of all those holes plus any extra "heap reserved" space above the highest heap entry.

To get the current stack usage you need to know two things:

  1. The staring address of the stack, and
  2. The current extent of the stack

Item 1 will be a fixed value, though what that value is I have no clue, but some reading will surely give you that value.

Item 2 can be obtained by allocating a local variable in a function and getting the address of that variable.

If all you care about is the change in stack imposed by your code you can record the "starting" stack point and use that in point 1. For example:

char *stack_start;

void setup() {
    char stack;
    stack_start = &stack;
}

Then you can use that to get the current stack size compared to the start of your program:

uint32_t stack_size() {
    char stack;
    return (uint32_t)stack_start - (uint32_t)&stack;
}

one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

No. Use of String and other dynamic allocation is what causes memory fragmentation.

  • but isnt "asd asd" a string? and that stack code seems really useful thanks. – alphaceph Apr 9 '20 at 12:10
  • It's a "string literal", not a String. A String is specifically an instance of the (Arduino specific) String class. – Majenko Apr 9 '20 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.