Use platformio.ini values in #define macro

I’m relatively certain I’m going to kick myself for asking this; I’m sure I know how to do this but I’m probably just not putting together the pieces. I’d like to be able to access values from the platformio.ini file within my sketch’s macros. Something like:

#define BAUD monitor_speed

… be gentle. :slight_smile:

This seems to be the prime example for the usage of build_flags. E.g., doing

build_flags = -D BAUD=115200

Will make the macro BAUD with a value of 115200 visible to every codefile in the project, so you can do Serial.begin(BAUD); in the code. Of course macros can be chained, so e.g.

build_flags = -D monitor_speed=115200

and then

#define BAUD monitor_speed

void setup() { Serial.begin(BAUD); }

is also possible but redudant in this case.

Thank you @maxgerhardt! What I ended up using along those lines was this:

build_flags = -D BAUD=${common_env_data.monitor_speed}

That way I only had to define the speed once with:

monitor_speed = 74880

I guess I failed to realize build_flags were so versatile!

1 Like

Follow-up: I thought that worked but I was mistaken. I went back to the following in platformio.ini:

build_flags = -D monitor_speed=115200

And the following in my sketch:

#define BAUD monitor_speed

I’d like to define the speed once, but this is much better than having to put it both in the sketch and in the ini. My end goal here is a template sketch that I can spin up quickly for testing.