Sub topic 6
Saving RAM with the `F()` Macro
This chapter assumes that you can upload a sketch, use setup() and loop(), and understand variables and function calls. It focuses on Arduino boards with AVR-style memory, such as the Uno and Nano.
Why string literals use RAM
A string literal is text written inside quotation marks, such as "Temperature:". On an AVR Arduino, a normal string literal is usually copied into SRAM when the sketch starts.
SRAM is the small, working memory used for variables and temporary data. An Uno has only 2 KB of SRAM. A few long messages can consume a large part of it.
Flash memory stores the uploaded program and is much larger. Text that never changes can remain in flash instead of being copied to SRAM. The F() macro tells Arduino to keep a string literal in flash.
Using `F()` with serial output
Pass the string to F() when you print it:
void setup() {
Serial.begin(9600);
Serial.println(F("Arduino started"));
Serial.print(F("Analog value: "));
Serial.println(analogRead(A0));
}
void loop() {
}F("Arduino started") creates a flash-resident string. Serial.println() has an overload that knows how to read this type of string from flash.
Use F() for fixed messages. Do not use it for a variable:
char message[] = "Ready";
// Serial.println(F(message)); // Incorrect
Serial.println(message); // CorrectThe argument to F() must be a string literal, not a variable.
| Code | Typical storage on AVR Arduino | Use |
|---|---|---|
| `Serial.println("Ready");` | SRAM | Short or temporary text |
| `Serial.println(F("Ready"));` | Flash | Fixed text |
| `Serial.println(message);` | Depends on how `message` was declared | Text stored in a variable |
Combining flash text with values
Use F() for labels and pass values separately. This avoids constructing one large temporary string.
const int SENSOR_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(SENSOR_PIN);
Serial.print(F("raw="));
Serial.println(raw);
delay(500);
}You can also use F() in debug messages:
#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("Debug output enabled"));
}
void loop() {
DEBUG_PRINTLN(F("Loop is running"));
delay(1000);
}When DEBUG is 0, the debug macro expands to nothing. The debug calls do not produce output, and the fixed messages are not needed by the compiled sketch.
Choosing when to use it
Use F() when a message is constant and your board has limited SRAM. It is especially useful for menus, error messages, labels, and repeated debug text. On boards with more modern memory systems, the RAM saving may be smaller, but F() remains commonly supported for Arduino sketches.
Exercise
Rewrite Serial.println("Sensor disconnected"); so that the message is kept in flash on an AVR Arduino.
Show answer
Use Serial.println(F("Sensor disconnected"));.