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

MemoryUse
FlashProgram code & constants (PROGMEM)
SRAMVariables, arrays, stack/heap
EEPROMNon-volatile data storage (optional)

2. Reduce SRAM Usage (Key Focus Area)

Use F() Macro

Store string literals in Flash instead of SRAM:

cpp

Serial.print(F("This is stored in Flash"));

Use PROGMEM for Constant Data

Store arrays, strings, or lookup tables in program memory:

cpp

const char msg[] PROGMEM = "Hello";

Access with:

cpp

char buffer[6]; strcpy_P(buffer, msg);

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) with byte or uint8_t (8-bit) where possible.

  • Use float only when necessary (costly on 8-bit MCUs).

cpp

byte index = 0; // instead of int index = 0;

4. Reuse Memory Buffers

  • Avoid creating multiple temporary buffers.

  • Reuse char[] or String buffers if possible, especially inside loops.


5. Avoid String Class (on AVR boards)

  • String can fragment SRAM over time.

  • Use char arrays (c-strings) instead:

cpp

char name[] = "Arduino";

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., TinyWire instead of Wire, Adafruit_TinyGLCD instead of full GLCD).


8. Optimize Arrays

  • Use smaller arrays.

  • Use bit fields or bit flags to pack multiple values into a single byte.

cpp

uint8_t flags = 0b00000101; // Two boolean values in one byte

9. Use EEPROM for Persistent Data

Offload rarely used or persistent values (e.g., config settings):

cpp

#include <EEPROM.h> EEPROM.write(0, 42);

10. Use Compiler Optimizations

  • Enable LTO (Link-Time Optimization) in Arduino IDE settings.

  • Remove unused code sections with conditional #ifdef or compile-time flags.


 Summary Checklist

TipBenefit
Use F() and PROGMEMSaves SRAM
Use byte/uint8_t over intReduces variable size
Avoid String class (on AVR)Prevents fragmentation
Reuse buffers and variablesFrees SRAM
Offload data to EEPROM or FlashSRAM savings
Use minimal and optimized librariesShrinks Flash/SRAM use

评论

此博客中的热门博文

Detailed Explanation of STM32 HAL Library Clock System

How do you set up ADC (Analog-to-Digital Converter) in STM32?

How To Connect Stm32 To PC?