4

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?

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

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.

| improve this answer | |
  • 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 Sep 4 '16 at 13:43

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.