Is it possible to get environtment dependent values in cpp code?
In platformio.ini:
[env:env_custom_target]
platform = ...
value_one = "target 1"
[env:env_custom_target_2]
platform = ...
value_one = "target 2"
Then in my arduino code:
config.get("value_one");
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.,
[env:env_custom_target]
platform = ...
build_flags = -D DO_SOMETHING=1
[env:env_custom_target_2]
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.begin(115200);
#if DO_SOMETHING == 1
Serial.println("Configured for type 1");
#elif DO_SOMETHING == 2
Serial.println("Configured for type 2");
#endif
}
//...
See the documentation
1 Like
Wow, thank you. That was helping a lot.
I adapted it a bit though:
[env:env_custom_target]
platform = ...
build_flags = -D DEVICE_NAME="\"Stefan\""
upload_port = /dev/cu.SLAB_USBtoUART
[env:env_custom_target_2]
platform = ...
build_flags = -D DEVICE_NAME="\"Oskar\""
upload_port = /dev/cu.SLAB_USBtoUART28
Now we can actually use DEVICE_NAME in our code directly.
Example:
Serial.printf("startHere: I am %s, I received from %u msg=%s\n", DEVICE_NAME, from, msg.c_str());