How do you optimize memory usage in an Arduino sketch?
Optimizing memory usage in an Arduino sketch is crucial, especially on devices with limited SRAM (e.g. only 2 KB on the ATmega328P). Here's a guide on how to do it effectively:
1. Understand Arduino Memory Types
| Memory | Use |
|---|---|
| Flash | Program code & constants (PROGMEM) |
| SRAM | Variables, arrays, stack/heap |
| EEPROM | Non-volatile data storage (optional) |
2. Reduce SRAM Usage (Key Focus Area)
Use F() Macro
Store string literals in Flash instead of SRAM:
Use PROGMEM for Constant Data
Store arrays, strings, or lookup tables in program memory:
Access with:
Minimize Global Variables
Global variables are allocated in SRAM. Reduce usage or convert to const + PROGMEM where possible.
3. Use Smaller Data Types
-
Replace
int(16-bit) withbyteoruint8_t(8-bit) where possible. -
Use
floatonly when necessary (costly on 8-bit MCUs).
4. Reuse Memory Buffers
-
Avoid creating multiple temporary buffers.
-
Reuse
char[]orStringbuffers if possible, especially inside loops.
5. Avoid String Class (on AVR boards)
-
Stringcan fragment SRAM over time. -
Use
chararrays (c-strings) instead:
6. Monitor Memory Usage
Use tools and functions:
-
freeMemory()function (custom implementation). -
Check memory summary in Arduino IDE after compilation.
7. Optimize Libraries
-
Remove unused libraries or functions.
-
Use lightweight alternatives (e.g.,
TinyWireinstead ofWire,Adafruit_TinyGLCDinstead of fullGLCD).
8. Optimize Arrays
-
Use smaller arrays.
-
Use
bit fieldsorbit flagsto pack multiple values into a single byte.
9. Use EEPROM for Persistent Data
Offload rarely used or persistent values (e.g., config settings):
10. Use Compiler Optimizations
-
Enable LTO (Link-Time Optimization) in Arduino IDE settings.
-
Remove unused code sections with conditional
#ifdefor compile-time flags.
Summary Checklist
| Tip | Benefit |
|---|---|
Use F() and PROGMEM | Saves SRAM |
Use byte/uint8_t over int | Reduces variable size |
Avoid String class (on AVR) | Prevents fragmentation |
| Reuse buffers and variables | Frees SRAM |
| Offload data to EEPROM or Flash | SRAM savings |
| Use minimal and optimized libraries | Shrinks Flash/SRAM use |

评论
发表评论