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?

Greenonline
  • 2,938
  • 7
  • 32
  • 48
user3260462
  • 71
  • 1
  • 1
  • 2

1 Answers1

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.

Mikael Patel
  • 7,969
  • 2
  • 14
  • 21
  • 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 04 '16 at 13:43