U8g2 and F() strings

What's the best way to convert strings in PROGMEM to something U8g2's drawStr() can use?

If you try to display a string stored in PROGMEM with the F() macro:

disp.drawStr(32, 32, F("Hello."));

you'll get a compile time error:

U8g2lib.h:238:17: note:   no known conversion for argument 3 from 'const __FlashStringHelper*' to 'const char*'

Doing a reinterpret_cast<const char*> or using PSTR() instead of F() will let the code compile, but neither produces the desired output.

Can anyone suggest a solution that doesn't use more memory than the memory you're trying save by using F() in the first place?

The drawStr() does not support a string from flash as far as I know.
You can use strcpy_P() with a buffer on the stack or a common global buffer.

char buffer[40];

const char text1[] PROGMEM = "Hello.";

strcpy_P( buffer, text1);
disp.drawStr(32, 32, buffer);

Thanks, Koepel. I was hoping for/wondering if there was a solution that didn't involve an intermediary buffer. I suppose the answer probably is if you can't spare 20 or 40 bytes you might have bigger problems. :slight_smile:

The PSTR() should work as well, as a parameter for the strcpy_P() function. I use the sprintf_P() a lot for these situations.

char buffer[40];

strcpy_P( buffer, PSTR( "Hello"));
disp.drawStr(32, 32, buffer);

u8g2 also includes the Arduino print function:

disp.setCursor(32, 32);
disp.print(F("Hello."));

This is also available as an example here:

A more complex example is here:

Oliver

olikraus:
u8g2 also includes the Arduino print function:

Totally missed that. Thanks!