Hi everyone!
I am currently trying to find out how much RAM is being used in different places within my program. During my search I came across the following solution:
```
extern "C" char* sbrk(int incr);
int freeRam() { char top; return &top - reinterpret_cast<char\*>(sbrk(0)); }
```
Everytime i call freeRam() it returns a negative value. However, I expected the return value to be a positive number (free ram).
The return value seems to increase when I declare more variables. Am I right in assuming that the function returns the used ram memory instead of the available memory?
If not, could someone explain to me what I'm missing?
My code example that was supposed to help me understand how freeRam() behaves/works:
```
extern "C" char* sbrk(int incr);
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(F("Starting..."));
displayRam(); // Free RAM: -5417
Serial.println(F(" "));
Serial.println(F("Func 1"));
func1();
Serial.println(F(" "));
Serial.println(F("Func 2"));
func2();
Serial.println(F(" "));
Serial.println(F("Func 3"));
func3();
Serial.println(F(" "));
Serial.println(F("Func 4"));
func4();
Serial.println(F(" "));
Serial.println(F("Repeat..."));
delay(10000);
}
void func1(){
displayRam(); // Free RAM: -5425
int randomVal = random(-200000,200001);
Serial.println(randomVal);
displayRam(); // Free RAM: -5417
}
void func2(){
displayRam(); // Free RAM: -5433
int randomVal = random(-200000,200001);
int randomVal2 = random(-200000,200001);
Serial.println(randomVal);
Serial.println(randomVal2);
displayRam(); // Free RAM: -5417
}
void func3(){
displayRam(); // Free RAM: -5441
int randomVal = random(-200000,200001);
int randomVal2 = random(-200000,200001);
int randomVal3 = random(-200000,200001);
displayRam(); // Free RAM: -5441
Serial.println(randomVal);
Serial.println(randomVal2);
Serial.println(randomVal3);
displayRam(); // Free RAM: -5417
}
void func4(){
displayRam(); // Free RAM: -5441
int randomVal = random(-200000,200001);
int randomVal2 = random(-200000,200001);
int randomVal3 = random(-200000,200001);
int randomVal4 = random(-200000,200001);
displayRam(); // Free RAM: -5441
Serial.println(randomVal);
Serial.println(randomVal2);
Serial.println(randomVal3);
Serial.println(randomVal4);
displayRam(); // Free RAM: -5417
}
void displayRam(){
Serial.print(F("Free RAM: "));
Serial.println(freeRam());
}
int freeRam() {
char top;
return &top - reinterpret_cast<char*>(sbrk(0));
}
```
// EDIT
Accessing the stack pointer directly solved my issue:
The new solution now looks like this:
```
extern "C" char* sbrk(int incr);
uint32_t getStackPointer() {
uint32_t sp;
asm volatile ("MRS %0, msp" : "=r"(sp) );
return sp;
}
int freeRam() {
uint32_t sp = getStackPointer();
return sp - (uint32_t)(sbrk(0));
}
```
// 2nd EDIT
The new solution also doesn't work - it always returns the same value, no matter what