Get config variables in code

Is it possible to get environtment dependent values in cpp code?

In platformio.ini:

platform = ...
value_one = "target 1"

platform = ...
value_one = "target 2"

Then in my arduino code:


I’ve seen similar thing for external scripts, but it also uses the section key which I don’t want.

Motivation: This would make it possible to flash multiple devices at the same time with different configuration. I have multiple nodemcus connected via usb and multiple sections with different upload_port settings. Now I can flash multiple devices at the same time. It would now be cool to give them predefined individual ids based on their platformio.ini section.

Through build_flags you can control the flags given to the compiler (gcc/g++). There you can add a macro definition using -D MACRO_NAME=VALUE. E.g.,

platform = ...
build_flags = -D DO_SOMETHING=1

platform = ...
build_flags = -D DO_SOMETHING=2

In the code you can differentiate the paths by using #ifdef and #if <..> = <...> statements

#include <Arduino.h>

void setup() {
    Serial.println("Configured for type 1");
#elif DO_SOMETHING == 2
    Serial.println("Configured for type 2");

See the documentation

1 Like

Wow, thank you. That was helping a lot.
I adapted it a bit though:

platform = ...
build_flags = -D DEVICE_NAME="\"Stefan\""
upload_port = /dev/cu.SLAB_USBtoUART

platform = ...
build_flags = -D DEVICE_NAME="\"Oskar\""
upload_port = /dev/cu.SLAB_USBtoUART28

Now we can actually use DEVICE_NAME in our code directly.

  Serial.printf("startHere: I am %s, I received from %u msg=%s\n", DEVICE_NAME, from, msg.c_str());