The Arduino Reference PROGMEM page* has this example:
#include <avr/pgmspace.h>
const char string_0[] PROGMEM = "String 0"; // "String 0" etc are strings to store - change to suit.
const char string_1[] PROGMEM = "String 1";
const char string_2[] PROGMEM = "String 2";
const char string_3[] PROGMEM = "String 3";
const char string_4[] PROGMEM = "String 4";
const char string_5[] PROGMEM = "String 5";
// Then set up a table to refer to your strings.
const char *const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};
char buffer[30]; // make sure this is large enough for the largest string it must hold
void setup() {
Serial.begin(9600);
while (!Serial); // wait for serial port to connect. Needed for native USB
Serial.println("OK");
}
void loop() {
/* Using the string table in program memory requires the use of special functions to retrieve the data.
The strcpy_P function copies a string from program space to a string in RAM ("buffer").
Make sure your receiving string in RAM is large enough to hold whatever
you are retrieving from program space. */
for (int i = 0; i < 6; i++) {
strcpy_P(buffer, (char *)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing, just copy.
Serial.println(buffer);
delay(500);
}
}
I combined two lines and deleted a lot of the code, but the output is still exactly the same. Here's what I did, and I left the original code untouched but commented out:
for (int i = 0; i < 6; i++) {
Serial.println(string_table[i]);
// strcpy_P(buffer, (char *)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing, just copy.
// Serial.println(buffer);
delay(500);
}
Both versions run and produce the same output. Why have all those extra keywords, characters, and symbols? They don't seem to be doing anything that is apparent on the serial monitor since the simplified code does the same. Could the Serial.print be expanded/modified to show what it can do that the simplified code can't? (Or, put another way, what's the point in having it?)
- The link I gave doesn't work for some reason. Here it is:
PROGMEM - Arduino Reference