Sub topic 6
Saving RAM with the F() macro
This chapter assumes you can write a sketch with setup() and loop() and call Serial.print() and Serial.println(). It also assumes you know what a byte is and that a board has separate flash memory and RAM. The examples target AVR boards such as the Uno and Nano, where the problem is real. The last section covers other boards.
The problem: string literals use RAM
An Arduino Uno has 32 KB of flash and only 2 KB of SRAM. Flash holds your compiled program. SRAM holds global variables, the stack, and the heap, so it is the memory your sketch works in while it runs.
Every text literal you write, such as "Setup complete", has to be stored somewhere. On AVR chips, code and data live in separate address spaces (a Harvard architecture). The compiler stores the literal in flash, because that is where the program image goes. The normal C++ rule is that a const char* points into data memory, so the startup code also copies the literal into SRAM before setup() runs.
The result is that each literal exists twice. A debug-heavy sketch can fill SRAM with text that is only read once, in a Serial.println() call.
void setup() {
Serial.begin(9600);
Serial.println("Setup complete"); // 15 bytes in flash AND 15 bytes in SRAM
}
void loop() {
}"Setup complete" is 14 characters plus the terminating null byte, so 15 bytes of SRAM are used permanently. Twenty messages of that size take about 300 bytes, which is roughly 15% of the Uno's SRAM. Nothing in your variables accounts for it.
What F() does
F() is a macro defined by the Arduino core. It marks a string literal as flash-only and gives you a pointer of type const __FlashStringHelper*. The startup code does not copy such a string to SRAM. Instead, print() has an overload that accepts this pointer type and reads the characters straight from flash, one byte at a time.
void setup() {
Serial.begin(9600);
Serial.println(F("Setup complete")); // 15 bytes in flash only
}
void loop() {
}The output in the Serial Monitor is identical. The only difference is memory use.
Under the hood, F("text") expands to roughly reinterpret_cast<const __FlashStringHelper*>(PSTR("text")). PSTR is the AVR library macro that places a literal in program memory (PROGMEM). __FlashStringHelper is a dummy class. It exists so the compiler can pick the right print() overload and so you cannot pass the pointer to a function that expects a normal const char* by accident.
Measuring the difference
Guessing about memory is unreliable, so measure it. After you compile, the IDE's output panel reports a line like this:
Global variables use 210 bytes (10%) of dynamic memory, leaving 1838 bytes for local variables."Global variables" here includes the copied string literals. Compile the same sketch with and without F() and compare the two numbers. The difference is the total size of the strings you wrapped, including their null bytes.
The compile-time number does not include the stack or the heap. To see free memory while the sketch runs, use this helper. It works on AVR boards only, because it uses AVR linker symbols.
extern int __heap_start, *__brkval;
int freeRam() {
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}
void setup() {
Serial.begin(9600);
Serial.print(F("Free SRAM: "));
Serial.println(freeRam());
}
void loop() {
}Run it once with F() removed from the Serial.print() call and once with it in place. The reported free memory differs by the length of "Free SRAM: " plus one byte.
Where F() works and where it does not
F() helps only where the receiving function has a __FlashStringHelper* overload. These cases work:
| Use | Works? | Notes |
|---|---|---|
| `Serial.print(F("text"))` | Yes | The `Print` class has the overload. |
| `Serial.println(F("text"))` | Yes | Same overload. |
| `lcd.print(F("text"))` | Usually | Any library built on `Print` inherits it. |
| `String s = F("text");` | Yes | `String` has a constructor for flash strings, but it copies the text into heap RAM. |
| `strcmp(buf, F("text"))` | No | Compile error. Use `strcmp_P(buf, (PGM_P)F("text"))`. |
| `const char* p = F("text");` | No | Compile error, because the types differ. |
| `F("a") + x` | No | `+` is not defined for flash string pointers. |
| Global initializer such as `const char* msg = F("x");` | No | Same type mismatch. Use `PROGMEM` instead. |
The type error is deliberate. If a function expects const char*, the compiler stops you from passing it a pointer into flash, where an ordinary read would return the wrong bytes.
Passing flash strings to your own functions
If you write a helper that prints messages, declare its parameter with the flash type:
void logMessage(const __FlashStringHelper* msg) {
Serial.print(F("[log] "));
Serial.println(msg);
}
void setup() {
Serial.begin(9600);
logMessage(F("Sensor ready"));
}
void loop() {
}This version accepts only flash strings. To accept both kinds, write two overloads: one taking const char* and one taking const __FlashStringHelper*. Both can call Serial.println().
Strings you build at runtime
F() works only on literals that exist at compile time. Text you assemble with sprintf, String concatenation, or dtostrf lives in RAM regardless. For a label plus a value, print the pieces separately instead of building one string:
void printReading(int raw) {
Serial.print(F("raw=")); // label stays in flash
Serial.println(raw); // value is formatted on the fly
}This also avoids a temporary buffer.
Larger tables of text with PROGMEM
If you have an array of messages, F() cannot wrap the array. Store each string with PROGMEM and an array of pointers, then read them with strcpy_P or print them via a cast to __FlashStringHelper*. This is a bigger topic. For tracing and status output, F() is enough.
Combining F() with debug macros
The debug macros from a later chapter pass their argument straight to Serial.print(). That means you can wrap the literal at the call site:
#define DEBUG 1
#if DEBUG
#define DEBUG_PRINTLN(x) Serial.println(x)
#else
#define DEBUG_PRINTLN(x)
#endif
void setup() {
Serial.begin(9600);
DEBUG_PRINTLN(F("Entering setup"));
}
void loop() {
}When DEBUG is 0, the macro expands to nothing, so the literal disappears from the program entirely. When it is 1, F() keeps the literal out of SRAM. You get both savings with no extra code in the macro.
Symptoms of running out of SRAM
SRAM exhaustion rarely produces a clear error. The stack grows downward and the heap grows upward, and when they meet, memory is corrupted. Typical signs are:
- The board resets repeatedly or freezes after a certain number of lines are printed.
- Variables show impossible values.
- A sketch works until you add one more
Serial.println()call. - Text in the Serial Monitor becomes garbled partway through, even though the baud rate is correct.
If the compile output already reports more than about 75% dynamic memory used, wrap your literals in F() before looking anywhere else. The change is mechanical and carries almost no risk.
Other boards
On boards based on ARM, ESP8266, ESP32, and similar chips, flash and RAM share one address space. A literal in const storage is read directly from flash and is not copied to RAM, so the duplication problem does not exist. The Arduino core still defines F() on those boards, usually as a plain cast, so sketches that use it compile everywhere. On these boards it neither helps nor harms, so you can keep it for portability.
Summary
- On AVR boards, each string literal takes flash space and an equal amount of SRAM unless you wrap it in
F(). F("text")produces aconst __FlashStringHelper*, andprint()andprintln()read it directly from flash.- Use it for every constant label and message you print. Do not use it for text built at runtime.
- Check your result with the "Global variables use" line in the compile output or with a
freeRam()helper. - The type is deliberately incompatible with
const char*, so compile errors will show you whereF()does not fit.
Exercise
A sketch on an Uno prints Serial.println("Calibration complete, please remove the probe."); once in setup(). The text is 46 characters long. How many bytes of SRAM does wrapping the literal in F() save, and why does the compile output's flash figure barely change?
Show answer
It saves 47 bytes (46 characters plus the terminating null byte), because without F() the startup code copies the whole literal from flash into SRAM. The flash figure barely changes because the string is stored in flash in both versions. Only a small amount of extra code is added to read flash bytes, and that cost is paid once, not per string.
Exercise
This line fails to compile: const char* label = F("Temperature");. What is the error's cause, and how would you print the label correctly?
Show answer
F() returns a const __FlashStringHelper*, which is a different type from const char*, so the assignment is rejected. To print the label, pass the F() expression directly to the print function: Serial.print(F("Temperature"));. If you need to keep the pointer, declare it with the right type: const __FlashStringHelper* label = F("Temperature"); and then call Serial.print(label);.