💾

Understanding Microcontroller Memory Management

Aug 25, 2024

Lecture Notes: Microcontroller Memory

Introduction

  • Importance of understanding microcontroller memory due to limited space.
  • Writing code carefully to avoid memory overflow.
  • Focus on types of memory and code examples.

Types of Microcontroller Memory

Flash Memory

  • Non-volatile memory.
  • Used to store program code.
  • Contents remain even when powered off.

RAM (Random Access Memory)

  • Volatile memory.
  • Used for program variables and data.
  • Contents lost when powered off.

EEPROM

  • Optional smaller type of non-volatile memory.
  • Used mainly for storing configuration data (not covered in detail).

Memory Size Example

  • Example microcontroller: 16 KB Flash, 512 Bytes RAM.
  • Flash memory is usually larger than RAM in most microcontrollers.

Code Compilation Process

  1. Source Code
    • Written in C (example).
  2. Compilation
    • Compiler translates source code to machine code.
  3. Linking
    • Linker organizes machine code into sections based on layout specified in a link script.
  4. Execution
    • Flash programmer writes machine code to flash memory.
    • RAM is initialized during the startup code.

Compiler and Linker Roles

  • Compiler
    • Divides code into sections (text, BSS, data).
  • Linker
    • Uses link script to determine where sections go in memory.

Code Example: Memory Allocation

  • Using standard blink example to demonstrate memory allocation for variables.
  • Variables:
    • Global Variable: initialized, ends in data section (counts against RAM and Flash).
    • Constant Variable: identical values, ends in const section (only counts against Flash).
    • Uninitialized Global Variable: defaults to zero, ends in BSS (counts against RAM).
    • Local Variable: allocated on the stack during function execution.
    • Static Variable: behaves like global, initialized during startup code.

Memory Inspection

  • Use IDE Memory Browser to inspect RAM and Flash.
  • Map file shows where each variable is stored in memory.

Final Remarks on Memory Management

  • Optimize code to save Flash space (avoid floating-point operations, use simpler implementations).
  • Use tools to analyze memory usage:
    • elf size: check section sizes in executable.
    • readelf: inspect symbols and their sizes.

Recommendations

  • Choose microcontrollers with more memory than necessary to avoid optimization issues.
  • Balancing memory usage with performance needs is essential in embedded programming.