7

I'm new to the Arduino and do not quite understand the F() macro yet.

In my code, I have a String, and as I want to transfer it via WebServer, I need to write it to the answer.

Somehow I need to convert the String, to fit it into the fastrprintln() function.

String weather_json = getWeatherData();
char weather[2048];
weather_json.toCharArray(weather,2048);
client.fastrprintln(F(weather));

Do you have any idea for me?

3
  • What do you mean by "I need to write it to the answer."? Is that a typo? Commented Jan 8, 2016 at 10:28
  • The F() macro is for literals (eg. F("foo") ) not variables.
    – Nick Gammon
    Commented Jan 8, 2016 at 11:12
  • I need to convert the String, to fit it into the fastrprintln() function.” No, you don't: client.println(getWeatherData()); Commented Jan 8, 2016 at 13:19

1 Answer 1

11

The Arduino core macro F() takes a string literal and forces the compiler to put it in program memory. This reduces the amount of SRAM needed as the string is not copied to a data memory buffer. Special functions are required to access the data stored in program memory. The Arduino core hides a lot of the typical usages such as:

Serial.println(F("Hello world"));

Further details of the low level access program memory access may be found in the AVR GCC libc documentation. The F() macro is defined as:

class __FlashStringHelper;
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper*>(PSTR(string_literal)))

The FlashStringHelper class is used to help the compiler recognize this type of string literal when passed to Arduino functions. Below are some examples:

// String constructor with program memory string literal
String::String(const __FlashStringHelper *str);

// Print (Serial, etc) of program memory string literal
size_t Print::print(const __FlashStringHelper *);
size_t Print::println(const __FlashStringHelper *);

You should not use the Arduino core F() macro with anything other than a string literal.

1
  • I was having an issue with my program locking up so after reading your answer I added the F() macro to my string literals and that was literally all it took to resolve this issue. I must be lower on memory than I had previously imagined.. Anyway, thanks for introducing me to this lock-up saving macro.
    – Jacksonkr
    Commented Sep 4, 2016 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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