Sub topic 6
Storing lookup tables in flash with PROGMEM
This chapter assumes you can write and upload a sketch, read C/C++ arrays and pointers, and use the Serial Monitor. It also assumes you know the split between flash, SRAM and EEPROM from the earlier chapters. The examples target AVR boards such as the Uno (32 KB flash, 2 KB SRAM).
Why a constant table costs SRAM by default
Suppose you declare this at global scope:
const uint16_t thresholds[] = {100, 250, 500, 750, 1000};The word const does not move the array to flash on AVR. The AVR is a Harvard architecture chip with separate address spaces for code (flash) and data (SRAM). Ordinary pointer reads and array indexing always look in the data space. So the startup code copies the initial values from flash into SRAM before setup() runs.
The table is therefore stored twice. Flash holds the initial image, and SRAM holds the working copy for the whole run of the sketch. A 256-entry table of 16-bit values takes 512 bytes of a 2048-byte SRAM, a quarter of everything you have.
PROGMEM is a variable attribute from <avr/pgmspace.h>. It tells the linker to keep the data in flash only and not copy it to SRAM.
Declaring and reading a PROGMEM table
Place PROGMEM after the array name, and keep const in front. Then read each element with a pgm_read_* function that takes the element's address.
#include <avr/pgmspace.h>
const uint16_t thresholds[] PROGMEM = {100, 250, 500, 750, 1000};
const uint8_t thresholdCount = sizeof(thresholds) / sizeof(thresholds[0]);
void setup() {
Serial.begin(9600);
for (uint8_t i = 0; i < thresholdCount; i++) {
uint16_t value = pgm_read_word(&thresholds[i]);
Serial.println(value);
}
}
void loop() {
}Three details matter here:
sizeofstill works on a PROGMEM array. It is evaluated at compile time and never touches memory, so the usual element-count idiom is safe.pgm_read_word()takes an address, which is why the call uses&thresholds[i]. Writingpgm_read_word(thresholds[i])passes a value where an address belongs. It compiles and returns garbage.- Arduino sketches include
<avr/pgmspace.h>automatically throughArduino.h. Writing the include explicitly is harmless and makes the dependency visible.
Choosing the right read function
Pick the function that matches the element type. The result is a plain value, so assign it to a normal variable.
| Element type | Read function | Bytes read |
|---|---|---|
| `uint8_t`, `int8_t`, `char` | `pgm_read_byte(addr)` | 1 |
| `uint16_t`, `int16_t` | `pgm_read_word(addr)` | 2 |
| `uint32_t`, `int32_t` | `pgm_read_dword(addr)` | 4 |
| `float` | `pgm_read_float(addr)` | 4 |
| pointer | `pgm_read_ptr(addr)` | 2 on AVR |
The signed types need a cast so the sign is preserved. For example, int16_t v = (int16_t)pgm_read_word(&table[i]);.
A practical case: a waveform table
Lookup tables replace slow math. A 16-step sine wave scaled to 0 to 255 is a typical example. Computing sin() in floating point on an 8-bit chip takes far longer than one flash read.
#include <avr/pgmspace.h>
const uint8_t sineTable[] PROGMEM = {
128, 177, 218, 245, 255, 245, 218, 177,
128, 79, 38, 11, 1, 11, 38, 79
};
const uint8_t SINE_STEPS = sizeof(sineTable);
void setup() {
Serial.begin(9600);
for (uint8_t phase = 0; phase < SINE_STEPS; phase++) {
Serial.println(pgm_read_byte(&sineTable[phase]));
}
}
void loop() {
}sizeof(sineTable) equals the element count here because each element is one byte. Reading from flash costs a few extra CPU cycles per access compared with SRAM, which is rarely visible in a sketch that is not timing-critical.
Tables of strings
Text needs one more step. An array of const char* pointers cannot hold the text itself. Each string must be its own PROGMEM object, and the pointer table must also be in PROGMEM. Otherwise the pointers sit in SRAM, which is smaller than the strings but still costs 2 bytes per entry.
#include <avr/pgmspace.h>
const char nameIdle[] PROGMEM = "Idle";
const char nameRunning[] PROGMEM = "Running";
const char nameFault[] PROGMEM = "Fault";
const char* const stateNames[] PROGMEM = {nameIdle, nameRunning, nameFault};
const uint8_t STATE_COUNT = sizeof(stateNames) / sizeof(stateNames[0]);
void printState(uint8_t i) {
const char* p = (const char*)pgm_read_ptr(&stateNames[i]);
Serial.println((const __FlashStringHelper*)p);
}
void setup() {
Serial.begin(9600);
for (uint8_t i = 0; i < STATE_COUNT; i++) {
printState(i);
}
char buffer[10];
strcpy_P(buffer, (const char*)pgm_read_ptr(&stateNames[1]));
Serial.println(buffer);
}
void loop() {
}There are two ways to use a flash string:
- Print it directly.
Serial.print()andSerial.println()accept a__FlashStringHelper*. That is the typeF()produces, and the cast above produces the same type from your own pointer. - Copy it into a buffer with
strcpy_P(),strncpy_P()ormemcpy_P(), then use normal string functions. Size the buffer for the longest string plus the terminating zero.
Passing a flash pointer to a function that expects an SRAM string, such as plain Serial.println(const char*), prints whatever bytes sit at that SRAM address.
Tables of structs
For a table of records, read one field with a pgm_read_* call on the field's address, or copy the whole record into a local variable.
#include <avr/pgmspace.h>
struct Step {
uint16_t durationMs;
uint8_t level;
};
const Step sequence[] PROGMEM = {
{500, 10}, {250, 80}, {1000, 0}, {125, 255}
};
const uint8_t STEP_COUNT = sizeof(sequence) / sizeof(sequence[0]);
void setup() {
Serial.begin(9600);
for (uint8_t i = 0; i < STEP_COUNT; i++) {
Step s;
memcpy_P(&s, &sequence[i], sizeof(Step));
Serial.print(s.durationMs);
Serial.print(F(" ms, level "));
Serial.println(s.level);
}
}
void loop() {
}Copying the record with memcpy_P() is simpler than several field reads. The local s lives on the stack only for one loop pass, so the extra SRAM is the size of one record, not the whole table.
Confirming the saving in the build report
Compile the sketch once with PROGMEM and once without it. Compare the two lines in the build output:
- Global variables should drop by the size of the table (plus any pointer tables). This is the saving you are after.
- Program storage should stay about the same. The values were already in flash as the startup image, and now they are only stored there.
If the "Global variables" number did not fall, check that PROGMEM is on the right declaration and that the table is not also being copied somewhere else.
Gotchas and failure modes
- Local variables. Put PROGMEM tables at file scope, or mark them
staticinside a function. A plain local variable with PROGMEM is not reliable, and a local is normally built on the stack anyway. - Read-only. Flash cannot be modified by your sketch while it runs. If a value must change, it belongs in SRAM or EEPROM.
- The 64 KB limit.
pgm_read_*uses 16-bit addresses, so it reaches only the first 64 KB of flash. Boards with more flash, such as the Mega 2560 (256 KB), need thepgm_read_*_farfunctions and far addresses for data beyond that range. On a 32 KB Uno this does not arise. - Portability. Other cores handle this differently. On ARM boards such as the Uno R4,
constdata is read-only data in flash and ordinary reads work. Arduino cores definePROGMEMandpgm_read_*there as no-ops or plain reads, so code written for AVR usually still compiles. ESP8266 is the exception to check, because it has its own rules for flash access. If a sketch must run on both AVR and other boards, keep thepgm_read_*calls and test on each target. - Small tables. A table of eight bytes is not worth the extra code. The saving matters for tables of dozens of bytes and up, or for many strings.
Summary
Use const T name[] PROGMEM for read-only data that you index into, and read each element with the pgm_read_* function that matches its type. Use F() for one-off string literals in print calls, and use PROGMEM when the data is a table or must be selected by index. Confirm the result in the "Global variables" line of the build report.
Exercise
A sketch declares const uint16_t table[] PROGMEM = {10, 20, 30}; and then prints table[1] with Serial.println(table[1]);. It compiles but prints a wrong number. What is the cause, and what is the corrected statement?
Show answer
The array is in flash, but table[1] reads from the SRAM address space, so the program reads unrelated bytes. The corrected statement is Serial.println(pgm_read_word(&table[1]));, which reads the 16-bit value from flash and prints 20.
Exercise
A 300-element uint16_t lookup table is declared as a plain const global array. Roughly how much SRAM does it use on an Uno, and what should you expect in the build report after adding PROGMEM and pgm_read_word()?
Show answer
It uses 600 bytes of SRAM (300 elements × 2 bytes), about 29% of the Uno's 2048 bytes. After the change, "Global variables" should drop by about 600 bytes, and "Program storage" should stay about the same because the values were already stored in flash.