0
0
Embedded Cprogramming~15 mins

Memory layout on a microcontroller (Flash, SRAM, EEPROM) in Embedded C - Deep Dive

Choose your learning style9 modes available
Overview - Memory layout on a microcontroller (Flash, SRAM, EEPROM)
What is it?
Memory layout on a microcontroller refers to how different types of memory are organized and used inside the chip. The main types are Flash, SRAM, and EEPROM. Flash stores the program code permanently, SRAM holds temporary data while the program runs, and EEPROM keeps data even when power is off. Understanding this layout helps you write efficient and reliable embedded programs.
Why it matters
Without knowing the memory layout, you might put data in the wrong place, causing your program to crash or lose data. For example, if you store variables in Flash, they can't change during runtime. If you don't use EEPROM correctly, you might lose important settings when the device powers off. Good memory use ensures your device works smoothly and saves power.
Where it fits
Before this, you should know basic C programming and what variables and functions are. After this, you can learn about memory optimization, interrupts, and low-level hardware control. This topic is a foundation for writing embedded software that interacts directly with hardware.
Mental Model
Core Idea
A microcontroller's memory is like a small workshop with separate drawers for permanent tools (Flash), temporary notes (SRAM), and special locked boxes for important keepsakes (EEPROM).
Think of it like...
Imagine your desk at home: Flash is like your bookshelf where you keep your instruction manuals (program code) that don't change. SRAM is your desk surface where you work with papers and notes that you use and discard quickly. EEPROM is a locked drawer where you keep important documents you want to keep safe even if you leave the room.
┌─────────────┐
│   Flash     │  ← Stores program code, read-only during run
├─────────────┤
│    SRAM     │  ← Holds variables and data during execution
├─────────────┤
│   EEPROM    │  ← Stores data that must persist after power off
└─────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Flash Memory Basics
🤔
Concept: Flash memory stores the program code and constants permanently.
Flash memory is non-volatile, meaning it keeps data even when the power is off. When you write a program in C and compile it for a microcontroller, the compiled code is stored in Flash. The microcontroller reads instructions from Flash to run the program. You cannot change Flash content easily during normal operation; it requires special commands to erase and rewrite.
Result
Your program code is safely stored and runs from Flash every time the microcontroller powers on.
Knowing that Flash is permanent storage helps you understand why program code and fixed data go there, not variables that change.
2
FoundationRole of SRAM in Microcontrollers
🤔
Concept: SRAM is fast, temporary memory used for variables and data during program execution.
SRAM is volatile memory, which means it loses its content when power is off. It is used to store variables, stack, and heap during program run. When your program declares variables or uses function calls, the data lives in SRAM. It is faster to access than Flash but smaller in size.
Result
Variables and temporary data are stored in SRAM and are lost when the device powers off.
Understanding SRAM as temporary workspace clarifies why variables reset after power loss.
3
IntermediateEEPROM for Persistent Data Storage
🤔Before reading on: do you think EEPROM is faster or slower than SRAM? Commit to your answer.
Concept: EEPROM stores data that must remain after power off but is slower to access than SRAM.
EEPROM is non-volatile memory like Flash but designed for storing small amounts of data that change occasionally, such as device settings or calibration values. Unlike Flash, EEPROM can be rewritten byte-by-byte without erasing large blocks. However, writing to EEPROM is slower and has limited write cycles.
Result
Important data can be saved and retrieved across power cycles using EEPROM.
Knowing EEPROM's role prevents misuse of Flash or SRAM for persistent data, avoiding data loss.
4
IntermediateMemory Address Mapping and Usage
🤔Before reading on: do you think variables can be stored in Flash memory? Commit to your answer.
Concept: Each memory type has a specific address range and usage rules in the microcontroller.
Microcontrollers map Flash, SRAM, and EEPROM to different address ranges. The compiler and linker assign program code to Flash addresses and variables to SRAM addresses. Some microcontrollers allow reading EEPROM via special instructions or memory-mapped addresses. Understanding this mapping helps you debug memory issues and optimize usage.
Result
You can predict where your code and data live in memory and avoid conflicts.
Recognizing address mapping helps prevent bugs like trying to write to read-only Flash.
5
IntermediateDeclaring Variables in Different Memory Types
🤔Before reading on: do you think you can store a variable in EEPROM using normal C syntax? Commit to your answer.
Concept: Special keywords and techniques are needed to place variables in Flash or EEPROM instead of SRAM.
By default, variables are stored in SRAM. To store constants in Flash, you use keywords like 'const'. To store data in EEPROM, you often use special compiler attributes or functions. For example, in embedded C, you might declare 'const int x = 5;' to keep x in Flash. Writing to EEPROM requires special API calls because it is not directly writable like SRAM.
Result
You can control where data lives, improving memory efficiency and persistence.
Knowing how to declare variables in different memory types lets you optimize memory use and data persistence.
6
AdvancedMemory Constraints and Optimization Techniques
🤔Before reading on: do you think using too much SRAM can cause your program to crash? Commit to your answer.
Concept: Microcontrollers have limited memory, so efficient use of Flash, SRAM, and EEPROM is critical.
SRAM is usually the smallest memory and can run out quickly if you use large arrays or many variables. Flash size limits program complexity. EEPROM has limited write cycles, so frequent writes can wear it out. Techniques like storing constant strings in Flash, minimizing global variables, and buffering EEPROM writes help optimize memory use and device lifespan.
Result
Your program runs reliably without memory overflow or premature EEPROM wear.
Understanding memory limits guides you to write stable and efficient embedded software.
7
ExpertUnexpected Behaviors and Debugging Memory Issues
🤔Before reading on: do you think writing to a 'const' variable causes a compile error or runtime error? Commit to your answer.
Concept: Misusing memory types can cause subtle bugs like corrupted data, crashes, or unexpected resets.
Trying to write to Flash or 'const' variables causes undefined behavior or hardware faults. Stack overflow in SRAM can overwrite important data. EEPROM write failures can corrupt settings. Debugging tools like memory maps, watch windows, and hardware debuggers help find these issues. Understanding the hardware's memory protection and access rules is key to solving tricky bugs.
Result
You can diagnose and fix complex memory-related bugs in embedded systems.
Knowing how memory misuse manifests helps prevent costly debugging and device failures.
Under the Hood
The microcontroller's CPU fetches instructions from Flash memory because it is non-volatile and fast enough for code execution. SRAM is connected to the CPU via a fast data bus for quick read/write access to variables and stack during runtime. EEPROM uses a different internal circuit optimized for data retention and byte-level writes but with slower access times. The memory controller manages access permissions and timing for each memory type to ensure correct operation.
Why designed this way?
Flash was chosen for program storage because it retains data without power and can be erased and reprogrammed in blocks, balancing permanence and flexibility. SRAM is volatile but very fast and simple, ideal for temporary data. EEPROM provides a way to store small amounts of data persistently with byte-level access, which Flash cannot do efficiently. This separation balances speed, cost, power, and durability.
┌─────────────┐       ┌─────────────┐       ┌─────────────┐
│   Flash     │◄──────│   CPU Core  │──────►│    SRAM     │
│(Program &   │       │ (Executes   │       │ (Variables, │
│ Constants)  │       │  Instructions)│      │  Stack)     │
└─────────────┘       └─────────────┘       └─────────────┘
                             │
                             ▼
                      ┌─────────────┐
                      │   EEPROM    │
                      │(Persistent  │
                      │  Data)      │
                      └─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Can you modify variables stored in Flash during program execution? Commit to yes or no.
Common Belief:Variables declared as 'const' are stored in Flash but can be changed during runtime like normal variables.
Tap to reveal reality
Reality:Variables in Flash, especially 'const', are read-only during program execution and cannot be modified without special programming steps.
Why it matters:Trying to modify Flash variables causes program crashes or unpredictable behavior, wasting debugging time.
Quick: Does EEPROM have unlimited write cycles? Commit to yes or no.
Common Belief:EEPROM can be written to as many times as needed without any wear or failure.
Tap to reveal reality
Reality:EEPROM has a limited number of write cycles (typically 100,000 to 1,000,000), after which it may fail to store data reliably.
Why it matters:Ignoring EEPROM wear can cause data corruption and device malfunction in long-term use.
Quick: Is SRAM content preserved after power off? Commit to yes or no.
Common Belief:SRAM keeps its data even when the microcontroller is powered off.
Tap to reveal reality
Reality:SRAM is volatile memory and loses all data when power is removed.
Why it matters:Assuming SRAM is persistent leads to lost data and incorrect program behavior after resets.
Quick: Can you store large data arrays in EEPROM for fast access? Commit to yes or no.
Common Belief:EEPROM is suitable for storing large data arrays that need frequent access and updates.
Tap to reveal reality
Reality:EEPROM is slow and has limited write endurance, making it unsuitable for large or frequently changing data.
Why it matters:Using EEPROM improperly can slow down your program and wear out memory prematurely.
Expert Zone
1
Some microcontrollers allow executing code directly from SRAM (XIP), which can speed up certain operations but requires copying code from Flash at startup.
2
Flash memory erase operations happen in large blocks, so updating small data requires careful management to avoid erasing unrelated code.
3
Advanced compilers and linkers can place different parts of code and data into specific memory sections, enabling fine-grained control over memory layout.
When NOT to use
Avoid using EEPROM for frequently changing data like real-time sensor readings; use SRAM instead. Do not store large constant data in SRAM to save space; use Flash. For ultra-fast temporary data, specialized RAM or cache may be better than general SRAM.
Production Patterns
In production, critical calibration data is stored in EEPROM with wear-leveling algorithms to extend life. Firmware updates are stored in Flash with bootloader support. Variables are carefully placed to optimize SRAM usage, and constants are stored in Flash using 'const' qualifiers. Debugging memory layout issues often involves examining linker maps and using hardware debuggers.
Connections
Operating System Memory Management
Builds-on similar principles of separating code, data, and persistent storage.
Understanding microcontroller memory layout helps grasp how operating systems manage virtual memory and protect code and data.
Database Storage Systems
Shares the idea of balancing fast access memory with persistent storage for reliability.
Knowing microcontroller memory tradeoffs clarifies why databases use caches and disk storage differently.
Human Brain Memory Types
Analogous to short-term (SRAM), long-term (Flash), and special memory (EEPROM) storage in humans.
Recognizing this analogy deepens understanding of how different memory types serve distinct roles in information retention.
Common Pitfalls
#1Trying to write to a 'const' variable stored in Flash during runtime.
Wrong approach:const int x = 10; x = 20; // Attempt to change const variable
Correct approach:int x = 10; x = 20; // Use non-const variable in SRAM for changeable data
Root cause:Misunderstanding that 'const' variables are stored in read-only Flash memory.
#2Storing frequently updated data in EEPROM without wear management.
Wrong approach:void update_setting(int val) { eeprom_write(0x00, val); // Writes every time without delay }
Correct approach:void update_setting(int val) { static int last_val = -1; if (val != last_val) { eeprom_write(0x00, val); // Write only on change last_val = val; } }
Root cause:Ignoring EEPROM write cycle limits and not minimizing writes.
#3Declaring large arrays as global variables without considering SRAM size.
Wrong approach:int big_array[10000]; // May exceed SRAM size
Correct approach:Use Flash storage for large constant arrays or reduce array size: const int big_array[10000] = { ... }; // Stored in Flash
Root cause:Not accounting for limited SRAM capacity leading to memory overflow.
Key Takeaways
Microcontrollers have three main memory types: Flash for permanent code, SRAM for temporary data, and EEPROM for persistent data storage.
Flash memory is read-only during program execution and stores your program and constants safely across power cycles.
SRAM is fast but volatile memory used for variables and temporary data that disappear when power is lost.
EEPROM allows saving small amounts of data that must survive power loss but has slower access and limited write cycles.
Understanding how to use and declare data in these memories prevents bugs, optimizes performance, and extends device life.