I wonder if there is an easier way to print strings directly from flash without using a buffer or a loop (?)
See my example sketch below.
I define a string in Flash
const char string_0[] PROGMEM = "abcdefghijk";
const char string_1[] PROGMEM = "lmnopqrstu";
// and so on
then I set up a pointer table
const char* const string_table[] PROGMEM = {
string_0,
string_1,
string_2,
string_3,
string_4,
};
then it's easily possible to print directly from flash (without a buffer) with this "trick" I got from here: array of UTF-8 strings in FLASH (PROGMEM / strcpy_P / ...) - #16 by oqibidipo - Programming Questions - Arduino Forum
// example: flash_println(&string_table[i]);
void flash_println(const char* const* adress)
{
Serial.println(reinterpret_cast<const __FlashStringHelper *> pgm_read_word(adress));
}
but you have to do that with an indexed access (which is good for large arrays of strings...)
but if I want to access a particular string from flash by its native variable-name
without the use of my pointer table,
how can I do that in a similar "style" (like the function "flash_println()" shown above),
without the use of a buffer or a loop ?
Is that possible ?
(I think it is possible but I am lost between all the helper-macros and typecasts here )
(the classical way would be to use a loop like it is shown in the sketch below)
the example program:
const char string_0[] PROGMEM = "Check Inputs";
const char string_1[] PROGMEM = "Check Outputs";
const char string_2[] PROGMEM = "Setup/Configuration";
const char string_3[] PROGMEM = "Calibration";
const char string_4[] PROGMEM = "Exit";
// define a table with pointers to the menu strings (stored in flash memory)
const char* const string_table[] PROGMEM = {
string_0,
string_1,
string_2,
string_3,
string_4,
};
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
while(!Serial);
// print directly from flash:
// this works (printing via pointer-table):
flash_println(&string_table[0]);
flash_println(&string_table[1]);
// this doesn't work ():
//flash_println(&string_0[0]);
//flash_println(&string_1[0]);
// this works (using a loop):
flash_println_classic(&string_0[0]);
flash_println_classic(&string_1[0]);
}
void loop() {
// put your main code here, to run repeatedly:
}
// print directly from Flash without any buffer:
// from here: https://forum.arduino.cc/index.php?topic=360932.msg2490757#msg2490757
// example: flash_println(&string_table[i]);
void flash_println(const char* const* adress)
{
Serial.println(reinterpret_cast<const __FlashStringHelper *> pgm_read_word(adress));
}
// the classical way with a loop:
void flash_println_classic(const char* adress) {
int len = strlen_P(adress);
char myChar;
int k;
for (k = 0; k < len; k++)
{
myChar = pgm_read_byte_near(adress + k);
Serial.print(myChar);
}
Serial.println();
}