1

I want to know if it's possible to use the F() macro on text that is being passed to a function.

This is an example function:

void displayMenu(const char * txt, byte &var) {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(txt);
  lcd.setCursor(0, 1);
  lcd.print(var);
}

This is how I'm calling the function:

displayMenu("Backlight:", backlight);

If I didn't separate the repeating code into a separate function, I would've been able to write it out like this:

lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Backlight: "));
lcd.setCursor(0, 1);
lcd.print(var);

If I try to do:

displayMenu(F("Backlight"), backlight);

it doesn't work. Also if I try to do this in the function:

lcd.print(F(txt));

that also doesn't work.

I'm just wondering if such a thing is possible.

2

There is a special type for just this occasion - the __FlashStringHelper type.

void displayMenu(const __FlashStringHelper *txt, byte var) {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(txt);
  lcd.setCursor(0, 1);
  lcd.print(var);
}

Note I removed the & from var - you don't want that unless you are passing a complex class or are wanting to modify the contents of var in the function and have it reflected back outside the function. Passing a reference to a byte (&var) requires two bytes of data - just passing the content of a byte only requires one byte of data.

  • That's awesome! Thanks a lot! At first I was getting "cannot convert from type X to type Y..." errors, but I fixed it by enclosing all the passed text inside the macro, like this: displayMenu(F("Backlight"), backlight); And thanks for pointing out the & problem! I probably had accidentally copied that from an older function I was using that actually needed to modify the passed variable. – Jerry Nov 14 '15 at 16:11
  • I feel silly for asking the following, and I'm sure it's just the "Everything feels snappier!" bug, but just to confirm... Is there any way that this change in the code might've perceptibly increased the lcd display speed, like when switching between menus? – Jerry Nov 14 '15 at 16:13
  • The removing of the & may have had a very slight effect on the speed, but it's unlikely the text changes have done anything... – Majenko Nov 14 '15 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.