Description
Keep constant data in flash (program) memory only, instead of copying it to SRAM when the program starts. There’s a description of the various types of memory available on an Arduino board.
The PROGMEM
keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "keep this information in flash memory only", instead of copying it to SRAM at start up, like it would normally do.
PROGMEM is part of the pgmspace.h library. It is included automatically in the Arduino IDE.
While PROGMEM
could be used on a single variable, it is really only worth the fuss if you have a larger block of data that needs to be stored, which is usually easiest in an array, (or another C++ data structure beyond our present discussion).
Using PROGMEM
is a two-step procedure. Once a variable has been defined with PROGMEM
, it cannot be read like a regular SRAM-based variable: you have to read it using specific functions, also defined in pgmspace.h.
==== Important Note!
PROGMEM
is useful only when working with AVR boards (Uno Rev3, Leonardo etc.). Newer boards (Due, MKR WiFi 1010, GIGA R1 WiFi etc.) automatically use the program space when a variable is declared as a const
. However, for retro compatibility, PROGMEM
can still be used with newer boards. This implementation currently lives here.
Syntax
const dataType variableName[] PROGMEM = {data0, data1, data3…};
Note that because PROGMEM is a variable modifier, there is no hard and fast rule about where it should go, so the Arduino compiler accepts all of the definitions below, which are also synonymous. However, experiments have indicated that, in various versions of Arduino (having to do with GCC version), PROGMEM may work in one location and not in another. The "string table" example below has been tested to work with Arduino 13. Earlier versions of the IDE may work better if PROGMEM is included after the variable name.
const dataType variableName[] PROGMEM = {}; // use this form
const PROGMEM dataType variableName[] = {}; // or this one
const dataType PROGMEM variableName[] = {}; // not this one
Parameters
dataType
: Allowed data types: any variable type.
variableName
: the name for your array of data.