Sub topic 5
Keeping string literals out of SRAM with F()
This chapter assumes you can write and upload a sketch, you know C/C++ pointers and const, and you have used Serial.println(). It also assumes you know the earlier chapters' split between flash and SRAM, and that you are working on an AVR board such as the Uno (2 KB of SRAM, 32 KB of flash).
Why string literals cost SRAM
A string literal is text written directly in your code, such as "Sensor ready". Most sketches are full of them: log messages, menu text, error strings.
AVR chips use a Harvard architecture. Program code and data live in separate address spaces, and an ordinary pointer can only read SRAM. When you write this:
Serial.println("Sensor ready");the compiler has to make the characters reachable through an ordinary pointer. So it stores them in two places:
- In flash, as the initial value of the data.
- In SRAM, where the startup code copies them before
setup()runs.
Each literal costs its length plus one byte for the terminating '\0'. The SRAM copy exists for the whole life of the program, even if the message is printed once. On a board with 2048 bytes of SRAM, 30 messages of 25 characters take about 780 bytes. That is over a third of your memory, and the heap and stack must share what is left.
What F() does
F() is a macro defined by the Arduino core. It does two things:
- It places the literal in flash only, using the same mechanism as
PSTR()andPROGMEM. No SRAM copy is made. - It casts the resulting pointer to the type
const __FlashStringHelper *.
That special pointer type is a marker. It tells the compiler "this address is in flash, not SRAM". The Print class, which Serial, LCD libraries and many others inherit from, has an overload of print() and println() that accepts this type. That overload reads the text one byte at a time with pgm_read_byte().
void setup() {
Serial.begin(9600);
Serial.println(F("Starting sensor self-test..."));
Serial.println(F("Calibration table loaded."));
Serial.println(F("Ready for measurements."));
}
void loop() {
}These three literals are 28, 25 and 23 characters long. With the terminators, they would take 29 + 26 + 24 = 79 bytes of SRAM if written as plain literals. With F(), the "Global variables use" figure in the build report drops by 79 bytes. Flash usage barely changes, because the text was in flash before as well. The only addition is the small loop in the core that reads flash.
Measuring the effect
Do not trust the claim, measure it. Compile the sketch once with plain literals and once with F(), and compare the line in the Arduino IDE output that reads like this:
Global variables use 215 bytes (10%) of dynamic memory, leaving 1833 bytes for local variables.Your numbers will differ with the core version and libraries. What matters is the difference between the two builds. The freeRam() helper from the earlier chapter gives the same comparison at run time:
extern int __heap_start;
extern int *__brkval;
int freeRam() {
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}
void setup() {
Serial.begin(9600);
Serial.print(F("Free RAM: "));
Serial.println(freeRam());
Serial.println("This literal is copied into SRAM at startup.");
}
void loop() {
}Remove the F() from the first print() and the reported number drops by 11 bytes, the length of Free RAM: plus its terminator.
Where F() works and where it does not
F() only helps where the receiving code knows it got a flash pointer. The type system enforces this: passing F("text") to a function that expects const char * is a compile error, not a silent bug.
| Use | Works with F()? | Notes |
|---|---|---|
| `Serial.print(F("x"))`, `println` | Yes | `Print` has a flash overload |
| `lcd.print(F("x"))` | Usually | Works if the library derives from `Print` |
| `String s = F("x");` or `s += F("x");` | Yes | `String` has flash constructors and operators |
| `strcmp(buf, F("x"))` | No | Compile error. Use `strcmp_P(buf, PSTR("x"))` |
| `snprintf(buf, n, F("x"))` | No | Use `snprintf_P(buf, n, PSTR("x"))` |
| Global initializer such as `const char *p = F("x");` | No | `F()` must be used inside a function |
| Function taking `const char *` | No | Change the parameter type, see below |
Passing flash strings to your own functions
Declare the parameter as const __FlashStringHelper *. You can then hand it straight to print().
void logMessage(const __FlashStringHelper *msg) {
Serial.print(F("[log] "));
Serial.println(msg);
}
void setup() {
Serial.begin(9600);
logMessage(F("Motor started"));
logMessage(F("Motor stopped"));
}
void loop() {
}A function that is called with F() at every call site keeps all those texts in flash. The function itself stays small.
Choosing between two texts
Both branches of a conditional must have the same type. Two F() literals do, so this works:
bool relayOn = true;
Serial.println(relayOn ? F("Relay ON") : F("Relay OFF"));Mixing one F() and one plain literal does not compile, because the types differ.
Flash strings and the C library: the _P functions
AVR libc provides a _P version of the common string functions. The suffix means the argument marked as such points into flash. You mark the literal with PSTR(), the plain-pointer cousin of F().
#include <avr/pgmspace.h>
char command[16] = "start";
char line[32];
void setup() {
Serial.begin(9600);
if (strcmp_P(command, PSTR("start")) == 0) {
int temperature = 23;
snprintf_P(line, sizeof(line), PSTR("Temp: %d C"), temperature);
Serial.println(line);
}
}
void loop() {
}In strcmp_P() the flash argument is the second one. In snprintf_P() it is the format string. The %s conversion expects an SRAM pointer, but %S (capital) expects a flash pointer, so snprintf_P(buf, n, PSTR("Mode: %S"), flashPtr) works. Check the argument position in the AVR libc documentation for each function. Getting it wrong compiles and then prints garbage.
Strings you define once and use many times
F() creates a separate flash copy at each use. If the same text appears in six places, the compiler is not required to merge them, and you may pay for six copies in flash. Flash is usually less scarce than SRAM, but for repeated text, define it once with PROGMEM and cast at the point of use:
#include <avr/pgmspace.h>
const char errorText[] PROGMEM = "Sensor read failed";
void setup() {
Serial.begin(9600);
Serial.println(reinterpret_cast<const __FlashStringHelper *>(errorText));
}
void loop() {
}This also solves the "global scope" limit: a PROGMEM array can be declared outside any function. The next chapter covers PROGMEM tables in more detail.
Reading a flash string by hand
It helps to know what the Print overload does for you. This function does the same job with a byte loop:
#include <avr/pgmspace.h>
void printFlash(const __FlashStringHelper *text) {
const char *p = reinterpret_cast<const char *>(text);
char c;
while ((c = pgm_read_byte(p++)) != '\0') {
Serial.write(c);
}
}
void setup() {
Serial.begin(9600);
printFlash(F("Read one byte at a time from flash"));
Serial.println();
}
void loop() {
}pgm_read_byte() takes a flash address and returns the byte stored there. A plain *p would read the SRAM byte at that numeric address and return unrelated data. This is also why the flash overload is a little slower than the SRAM one: every byte needs a special load instruction (lpm). For serial output at 9600 baud the difference is invisible, since the port is the bottleneck.
Common errors
- Compile error "invalid conversion from
const __FlashStringHelper*toconst char*". You passedF()to a function that reads SRAM. Use a_Pfunction or change the parameter type. - Garbage output. A flash pointer was passed where SRAM was expected, usually through a cast, or
%swas used where%Swas needed. - Little or no saving. Your messages are short, or most of your SRAM goes to arrays and
Stringobjects. Check the build report before optimizing strings. - No effect on a non-AVR board. On ARM-based boards, ESP32 and others that share one address space,
F()often compiles to a plain pointer cast, so it does nothing. It is safe to leave in portable code.
Exercises
Exercise
A sketch has 12 plain Serial.println("...") calls, each with a 40-character literal. How many bytes of SRAM does F() save on an Uno, and what fraction of its SRAM is that?
Show answer
Each literal takes 40 + 1 = 41 bytes of SRAM, so 12 × 41 = 492 bytes. The Uno has 2048 bytes of SRAM, so that is about 24%.
Exercise
The line if (strcmp(input, F("stop")) == 0) does not compile. Why, and how do you fix it?
Show answer
strcmp() expects two SRAM pointers, but F() returns a const __FlashStringHelper *, which the compiler will not convert to const char *. Use the flash-aware version with PSTR(): if (strcmp_P(input, PSTR("stop")) == 0).