Arduino: Is the command Serial.print(“some string text”) occupying SRAM?

痴心易碎 提交于 2019-12-04 09:58:19

问题


I have quite a big Arduino project (in eclipse) going on with a lot of debug messages using the Serial.print("some string text") commands so that I can debug along the way.

One thing that I have noticed is that I reach a limit for how many of these I can have in the project. If i put too many, the program halts at very strange places. Ie: often long before my newest addition of a print command is supposed to execute.

My project .hex file is around 20k at the moment. The Arduino Uno limits around 30kb right? So it should not be too big.

So I feel that the actual problem is probably that maybe these serial commands are filling up my sram. Which is just 2kb. I am using a lot of libraries.

Is the command Serial.print("some string text") occupying SRAM? Surely gcc puts these string cnstants are in program space? but maybe they are not?

Or is it something else? I have an alternative theory that there is a serial.print buffer somewhere, and I am probably just filling it up with too many messages.


回答1:


Yup, string are stored in RAM by default. Although they're in the Flash memory too, but they're loaded into RAM when the Arduino boots.

However, if you use The Arduino IDE version 1.0 or later you can tell the compiler to read strings directly from Flash and not to bother loading them into RAM with the F() macro:

Serial.Println(F("This string is read from Flash!"));

This will save RAM which is a good thing as there's much less RAM than Flash. See here for more details: * http://www.arduino.cc/playground/Main/Printf




回答2:


This is not my code, but I find that the solution at: http://www.utopiamechanicus.com/article/low-memory-serial-print/ is very good for debugging. A decent combination of printf, flash memory usage, and macros so conversion is often as easy as removing the '.' from Serial.print().

I am a total noob to C++ and arduino though, hope someone finds it useful.




回答3:


Please try and mark the strings as PROGMEM, which should place them in the flash. Arduino does not seem to have Serial.write implemented for PROGMEM, so a mem-copy is required. See http://arduino.cc/en/Reference/PROGMEM (String arrays) for details.

EDIT: http://deans-avr-tutorials.googlecode.com/svn/trunk/Progmem/Output/Progmem.pdf explains the PROGMEM argument nicely.




回答4:


Yes it get's stored in RAM by default. You can use the solution by @Marty.

Alternatively you can also use MemoryFree library to keep track of your memory.



来源:https://stackoverflow.com/questions/12807871/arduino-is-the-command-serial-printsome-string-text-occupying-sram

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!