Memory limits

Hi,

I have very small arduino code but I use too many Serial.print("Type your name")... Serial.print("Type your age")... After increasing this serial messages my program became completely unstable. I believe it's lack of memory cause my atmega328p only has 2048KB of SRAM.

My question is this: I have no more than 10 variables of type int in my code. How am I running without memory? Are those strings in the Serial.print saved in the SRAM when arduino starts?

Are those strings in the Serial.print saved in the SRAM when arduino starts?

Yes. It's essentially an artifact of C that since the strings are "data", they have to appear in the RAM of cpus that have separate code/data address spaces. You can get around this by using the F construct (an arduino special feature.) http://arduino.cc/en/Serial/Print

You can pass flash-memory based strings to Serial.print() by wrapping them with F(). For example :

  • Serial.print(F(“Hello World”))

char x = "ABCDEFGHIJ"; You need an array here.

chars are only one byte in (most?) C.

char x[] = "ABCDEFGHIJ";

Will use 11 bytes of RAM. (don’t forget the terminating null.)

atmega328p only has 2048KB of SRAM.

Nope. 2048 bytes.

gilperon: Thank, you are indeed right, it should be an array. But will it only use 11 bytes of RAM or every variable that has that value will also consume 11 bytes of RAM?

After compilation ("Verify"), Arduino IDE 1.5.8 shows you how much RAM is taken by global variables, so you can try and see for yourself. Char arrays do not have common references - each occupies its own space, no matter what.

char x[] = "ABCDEFGHIJ";
Serial.println(x);
Serial.println(x);

Char arrays do not have common references - each occupies its own space, no matter what.

However, "x" in the println does NOT create another copy of the string in RAM, just a "pointer" to it, so the above program segment would still only use 11 bytes of RAM.

The "occupies its own space" thing comes into play with code like:

char x[] = "ABCDEFGHIJ";
char y[] = "ABCDEFGHIJ";

which gives you 22 bytes of storage used...

In the arduino docs it says that the compiler tries to identify the same string that appears in the code and if it appears more than once it will be saved only once in the Flash and SRAM, and will use a pointer to wherever that same string is being used.

char a [] = "0123456";
char b [] = "0123456";

...
.... and then later
a[1] = 'B';

Now, I can see that the same initial string can exist in flash, but that's simply not going to apply to RAM.

gilperon: Hi @westfw thank you for helping but I think you made a mistake. In the arduino docs it says that the compiler tries to identify the same string that appears in the code and if it appears more than once it will be saved only once in the Flash and SRAM, and will use a pointer to wherever that same string is being used.

That only applies in this sort of case:

Serial.println ("foo");
...
Serial.println ("foo");