Inject Board Name into Code

So what I am trying to accomplish is to use the board type (the board = lolin_d32 entry) in my code as a macro. The use case, for instance, is allowing the running firmware to pull down down the correct firmware for the board as an OTA upgrade.

There are two places I can think of pulling it:


However, from what I have been able to determine, I cannot create a build flag that is available in the sketch via an extra_scripts. I know I can put a determinate build flag in the platformio.ini but that seems inelegant since it’s a place I can make a silly mistake as I add more board types in the future.

I have seen an answer pointing out that there are platform/board flags defined, however, what I am looking for is the simple board name. Using those flags I would need to add explicit code for each board like this:

    String x = "lolin_d32";
    String x = "unknown";

I would greatly prefer to use something simple and that does not require edits/additions as I expand, such as:

String x = BOARD;

This does not seem possible unless I’m missing something simple?

String escaping is a common trap I’ve encountered many times when trying to inject string variables. See e.g. Injection of version of the computed libraries - #2 by maxgerhardt

This seems to work

platform = atmelavr
board = uno
framework = arduino
extra_scripts =

board = env["BOARD"]

macro_value = "\\\"" + board + "\\\""

  ("PLATFORMIO_BOARD", macro_value)


#include <Arduino.h>

void setup() {
  String used_board = PLATFORMIO_BOARD;
  Serial.println("Used board is: " + used_board);

void loop() { }

that compiles. Couldn’t test it right now.


You win the Interwebz, sir. That works!

Thank you - I’ll go read that other thread as well to understand your warning.

I wanted to share something I did a little differently. Since stringification is a thing when using these macros, I picked up a little macro goodness somewhere (I do not remember where):

#define stringify(s) _stringifyDo(s)
#define _stringifyDo(s) #s

Then I can just stringify(MACRO_NAME) and I’m golden. Using that, my script is: