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
Serial.begin(BAUD);

… 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
Serial.begin(BAUD);

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.

This is working for me:
platformio.ini

; PlatformIO Project Configuration File
;
;   Build options: build flags, source filter
;   Upload options: custom upload port, speed and extra flags
;   Library options: dependencies, extra library storages
;   Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html

[env:nanoatmega328]
platform = atmelavr
board = nanoatmega328
framework = arduino
monitor_speed = 115200
build_flags =
	-D MONITOR_SPEED=${this.monitor_speed}

main.cpp

Serial.begin(MONITOR_SPEED);

See also

1 Like

I investigated this option, but if you have a lot of configuration data, the platformio.ini becomes unwieldy. I’ve turned to Jason Turner’s JSON2CPP, which turns your a JSON file into a structured header file turn to in your project (hence, the name turner’s). It uses some intimidating C++ constructs, but the idea of easily changing configuration files for new scenarios makes it worthwhile. Right now I’m trying to incorporate it into Platformio’s build process.