In our first #TuesdayTip we show you how to save RAM on your Arduino by storing text and strings in program memory instead of your RAM. Doing this makesy our programs easier to read. You also your code avoid being held up in delays, the C++ ternary operator and the watchdog timer.
To save your string in the program memory, write
Serial.println(F("Hello World!"));
instead of Serial.println(“Hello World”);
When you write:
Serial.println("Hello World!");
the text ‘Hello World!’ is stored in two places:
- Program memory
- Random access memory (RAM)
The contents of RAM are lost every time the Arduino is reset, or the power is lost. Program memory is retained through reset and power loss, so at the start of each program, normal strings are copied from program memory into RAM so they can be used by your program.
Many Arduino boards don’t have much RAM though: there’s only 2 kb on the 328 chip used in the Uno, for example. So it is easy to run out of RAM if your program uses many strings or other variables.
When you write:
Serial.println(F("Hello World!"));
The println function gets the text from program memory directly, using a temporary buffer that doesn’t eat up lots of precious RAM.
Hope this helped with current or future projects you likely will be working on, do stay tuned for more next week on #TuesdayTips.