-->
Page 1 of 2

declare big array

PostPosted: Sat Sep 12, 2015 8:49 am
by woodwax
Hello

I developing weather station I would like to memorize some temperature and humidity values. But I have a problem with this.

I build a simple project to illustrate the problem. Here is the code:

Code: Select allvoid setup() {
Serial.begin(115200);
delay(3000);
Serial.println("begin");
}

//uint32_t temp[4000];                                //when I declare variable globally evrything is OK

void loop() {
  Serial.println("Variable declared");
  uint32_t temp[4000];                               //when I declare variable locally the program crash, wdt reset occours.
  while(1)
  {
    for(int i=0;i<4000;i++) temp[i]=i;
    Serial.println("This is test of on big array in ESP8266");
    Serial.println(temp[7]);
    delay(1000);
  }
}


When I declare the temp array globally evrything is OK, but when I declare it locally the program crash, wdt reset occours.

Can anyone help me why this crash occours? Is too big? Its only: uint32_t = 4bytes x 4000 = 16 000byte ~ 16KB.

Re: declare big array

PostPosted: Sat Sep 12, 2015 9:12 am
by martinayotte
Declaring local variables means they are allocated in the stack.
But since there are multiple contexts, such Wifi, and another for the Arduino loop(), there are many stacks.
So, those stacks need to be limited. From my understanding of cores/esp8266/cont.h, the stack per context is limited to 4096 bytes.

But why do you declared it locally ? (Leaving it in global is the way to go if you wish to keep data for other threads.)
And why do you have a "while(1)" inside the loop() ?
It goes against the arduino loop() philosophy.

Re: declare big array

PostPosted: Sat Sep 12, 2015 10:19 am
by woodwax
Thank you for the answer.

But why do you declared it locally ? (Leaving it in global is the way to go if you wish to keep data for other threads.)

Because in the school we learned that the correct way is to have fewer global variables. The best way declare them locally then pass them to functions by adress.

But my solution can be, to declare them globally and pass them to the function by adress.

And why do you have a "while(1)" inside the loop() ?


This was because the loop is called periodically and i dont want to redeclare variable every loop (if in my weather station program I declare memorized temperature array locally its value in every loop will be deleted. That is why I have there while() - to prevent redeclaration and deleting variable).
But if I declare the array globally I dont need it.

Re: declare big array

PostPosted: Sat Sep 12, 2015 11:46 am
by martinayotte
Your point is right as a best practice for simple variables.
But in this case, since it is a big array of data, it is not really applicable.
Just imagine if the networking itself would declare the packets buffer locally, that would be a problem to.
I think you now figured out ...