Sub topic 2
Keeping String Literals Out of SRAM with F()
This chapter assumes you can upload a sketch, know C/C++ arrays and pointers, and use the Serial Monitor. The examples target an AVR board such as the Uno, which has 32 KB of flash and 2 KB of SRAM.
Why string literals waste SRAM
A string literal is text in quotes. On AVR boards, Serial.println("Sensor ready"); copies that text into SRAM at startup, even though it never changes. The F() macro keeps the text in flash, which is much larger and keeps its contents without power.
void setup() {
Serial.begin(9600);
Serial.println(F("Sensor ready"));
}
void loop() {
}Use F() with the Serial print functions. You cannot assign F("...") to a plain char * variable.
Storing lookup tables in flash with PROGMEM
PROGMEM is a keyword that places a constant array in flash. Its values must be read with pgm_read_word() (or the matching accessor for the element size). Plain indexing reads the wrong memory.
#include <avr/pgmspace.h>
const uint16_t thresholds[] PROGMEM = {100, 250, 500, 750, 1000};
void setup() {
Serial.begin(9600);
for (uint8_t i = 0; i < 5; i++) {
uint16_t value = pgm_read_word(&thresholds[i]);
Serial.println(value);
}
}
void loop() {
}Measuring free RAM while the sketch runs
The compiler's memory report shows static use only. It does not show how much RAM remains while functions run. This helper estimates the gap between the top of the heap and the current stack position.
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());
}
void loop() {
}Why dynamic allocation fragments a 2 KB heap
The heap grows upward from the static data, and the stack grows downward toward it. Each malloc or String growth step allocates a new block and frees the old one. Freed blocks of different sizes leave gaps too small to reuse, so free memory exists but cannot hold a large request. Calling reserve() on a String allocates once. Fixed-size buffers avoid the heap entirely.
Exercise
Exercise
Which macro should you wrap around a constant string passed to Serial.println() to keep it in flash?
Show answer
F(). For example, Serial.println(F("Sensor ready")).