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:

env.GetProjectOption("board")
env["BOARD"]

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:

#ifdef ARDUINO_LOLIN_D32
    String x = "lolin_d32";
#else
    String x = "unknown";
#endif

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

[env:uno]
platform = atmelavr
board = uno
framework = arduino
extra_scripts = pre:inject_board.py

inject_board.py

Import("env")
board = env["BOARD"]

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

env.Append(CPPDEFINES=[
  ("PLATFORMIO_BOARD", macro_value)
])

src/main.cpp

#include <Arduino.h>

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

void loop() { }

that compiles. Couldn’t test it right now.

2 Likes

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:

Import("env")

env.Append(CPPDEFINES=[
  ("PLATFORMIO_BOARD", env["BOARD"])
])