Sub topic 1
Three kinds of memory: flash, SRAM and EEPROM
An Arduino Uno has three separate memories, and each one has a different job. Most memory problems on small boards come from putting data in the wrong one. This chapter explains what each memory holds, how fast and durable it is, and how a sketch ends up using all three.
Prerequisites
This chapter assumes you can do the following:
- Write, compile and upload a basic Arduino sketch.
- Read C/C++ code with variables, arrays, functions and pointers.
- Open the Serial Monitor and read what a sketch prints.
The numbers below are for the ATmega328P, the microcontroller on the Arduino Uno and Nano (the classic AVR boards). The last chapters of this tutorial cover other boards.
The three memories at a glance
A microcontroller is a computer on one chip, and its memory is much smaller than a PC's. The ATmega328P has these three areas:
| Memory | Size on an Uno | Keeps data without power? | Holds | Write endurance |
|---|---|---|---|---|
| Flash | 32 KB (about 0.5 KB used by the bootloader) | Yes | Your compiled program, plus constant data | About 10,000 erase/write cycles |
| SRAM | 2 KB | No | Variables while the program runs | Unlimited |
| EEPROM | 1 KB | Yes | Small settings you save on purpose | About 100,000 write cycles per byte |
The endurance figures are the minimum the manufacturer guarantees. Real chips often last longer, but you should design for the guaranteed numbers.
The sizes are very uneven. Flash is sixteen times larger than SRAM. A sketch that compiles to 20 KB is fine, but a sketch whose variables need 2.5 KB cannot run.
Flash: where your program lives
Flash memory stores the machine code that the compiler produces from your sketch. When you press Upload, the bootloader (a small program already on the chip) writes your code into flash. The data stays there when you unplug the board.
Three facts about flash matter for memory management:
- It is read-only while the sketch runs. Your code cannot change flash with ordinary assignments. Writing to flash needs a special procedure that normal sketches never use.
- It has limited write endurance. Each upload erases and rewrites flash. About 10,000 uploads is far more than most projects need, but flash is not a place to log data.
- It is a separate address space. The AVR uses a Harvard architecture, which means code and data are reached through different buses and different address spaces. A normal pointer such as
const char *ppoints into SRAM. It cannot point into flash.
The third fact explains why F() and PROGMEM exist. When data is in flash, the compiler must emit different instructions to read it (LPM, "load program memory") than it uses for SRAM. Plain C++ syntax cannot express that, so Arduino provides macros and helper functions. Later chapters cover them in detail.
SRAM: working memory
SRAM (static random-access memory) holds every variable your sketch uses while it runs. It is fast and has no wear limit. Its contents vanish when power is removed, and they are undefined when the chip first starts, which is why globals are initialized by startup code.
On the Uno, 2 KB is all you get. That space is shared by:
- global and static variables,
- the heap, used by
malloc(),newand theStringclass, - the stack, used for local variables and function calls.
On this chip, the 32 general-purpose registers and the I/O registers occupy the lowest addresses (up to 0x00FF). The usable SRAM runs from 0x0100 to 0x08FF, which is exactly 2048 bytes. The next chapter shows how those three consumers divide this space.
A key rule follows from this layout: when SRAM runs out, nothing warns you. The heap and stack grow toward each other, and if they meet, memory is silently corrupted.
EEPROM: small saved values
EEPROM (electrically erasable programmable read-only memory) keeps data without power, like flash. Unlike flash, your sketch can write to it while running, one byte at a time. That makes it the right place for settings that must survive a reset or power cycle, such as a calibration offset or a last-used mode.
It also has limits:
- It is small: 1 KB on the Uno.
- A write takes about 3.3 ms, which is very slow compared with an SRAM write.
- Each byte wears out after about 100,000 writes. Writing the same address in every
loop()pass could exhaust it in minutes.
The EEPROM library covers this: EEPROM.put() and EEPROM.get() store and read whole values. Both rewrite a byte only when its value changes (put() uses update() internally), which cuts wear.
#include <EEPROM.h>
struct Settings {
uint16_t interval;
uint8_t mode;
};
void setup() {
Serial.begin(9600);
Settings s = {1000, 2};
EEPROM.put(0, s);
Settings loaded;
EEPROM.get(0, loaded);
Serial.println(loaded.interval);
}
void loop() {
}This sketch saves a struct at address 0 and reads it back. Run it once and it prints 1000. Because the data is in EEPROM, a later sketch can read the same bytes with EEPROM.get(0, loaded), as long as it uses the same struct layout.
How the three memories fit together
When you upload a sketch, the data moves between memories in a fixed way. The compiler places code and constants in flash. At every reset, startup code copies initial values for globals into SRAM. The sketch may then read and write EEPROM on request.
One consequence is that initialized globals cost memory twice. For example, int table[] = {1, 2, 3}; takes space in flash (the initial values) and in SRAM (the live array). That is why constant tables benefit from PROGMEM: they then take space in flash only.
Checking the sizes on your own board
Rather than trust a table, you can have the board print its own memory sizes. The AVR headers define FLASHEND, RAMSTART, RAMEND and E2END as the last address of each memory (or, for SRAM, the first and last).
void setup() {
Serial.begin(9600);
Serial.print(F("Flash bytes: "));
Serial.println((unsigned long)FLASHEND + 1);
Serial.print(F("SRAM bytes: "));
Serial.println((unsigned long)(RAMEND - RAMSTART) + 1);
Serial.print(F("EEPROM bytes: "));
Serial.println((unsigned long)E2END + 1);
}
void loop() {
}On an Uno this prints 32768, 2048 and 1024. The flash figure includes the bootloader area, so your sketch has slightly less than 32768 bytes. The casts to unsigned long matter: on AVR an int is 16 bits, so adding to a value near 32767 could overflow a signed int.
The sketch also uses F() for its text labels. That keeps those strings in flash, which is the main topic of a later chapter. Without F(), each of these labels would also consume SRAM.
Common mistakes
These errors come up often when people first learn the three memories:
- Treating the compiler's flash number as the whole story. A sketch can use only 30% of flash and still crash because it uses 90% of SRAM. Flash is plentiful; SRAM is the scarce resource.
- Assuming constants are free in SRAM. A
constglobal array with initial values is still copied into SRAM on AVR unless you mark itPROGMEM. Addingconstalone does not move it. - Using EEPROM as scratch space. It is slow and wears out. Keep working values in SRAM and save only the final value.
- Expecting EEPROM to be erased on upload. Uploading a new sketch normally leaves EEPROM as it was. Old data from an earlier sketch will still be there, and a new sketch that reads an unwritten address gets
255(0xFF), the erased state. - Casting a flash address into a normal pointer. Reading flash data through an ordinary pointer returns wrong bytes, because the read goes to SRAM instead.
What comes next
The remaining chapters build on this division. First you will see exactly how SRAM is split into static data, heap and stack. Then you will read the compiler's memory report, shrink data types, move strings and tables to flash, and measure free RAM at run time. Later chapters cover heap fragmentation, the String class, stack usage and the symptoms of running out of memory.
Exercise
A sketch declares const int levels[] = {10, 20, 30, 40, 50, 60, 70, 80}; as a global and compiles fine on an Uno. Which memories hold data for this array while the sketch runs, and how many bytes does it use in each? What one change would remove the SRAM copy, and what must you change when reading it?
Show answer
The array has 8 elements of 2 bytes each (an int is 16 bits on AVR), so 16 bytes. The initial values are stored in flash, and startup code copies them into SRAM, so the array costs 16 bytes in flash and 16 bytes in SRAM. Adding PROGMEM (with #include <avr/pgmspace.h>) keeps the data only in flash. Then you can no longer use levels[i] to read it. You must use pgm_read_word(&levels[i]), because a normal read looks in SRAM.
Exercise
A weather logger saves the current temperature to EEPROM address 0 once per second, using EEPROM.write(). The EEPROM cells are rated for about 100,000 writes. Roughly how long until address 0 reaches its rated limit, and what should the design do instead?
Show answer
One write per second gives 100,000 seconds, which is about 27.8 hours (a little over a day). Instead, keep the temperature in SRAM and write to EEPROM only when needed, for example when the value changes by a meaningful amount, or on a shutdown or button-press event. If frequent logging is required, spread writes across many addresses (wear leveling) or use external storage such as an SD card. Using EEPROM.update() also avoids rewriting a byte that already holds the same value.