Go Down

Topic: Arduino CLI Pass Flags To Sketch (Read 1 time) previous topic - next topic

tclambert00

Oct 29, 2020, 02:45 pm Last Edit: Oct 29, 2020, 02:52 pm by tclambert00
Does the Arduino CLI compile command have the ability to pass arguments to the sketch, similar to using "sh file argument" and "ARG=$1" type shell scripting?

I have a project where I need certain code compiled based on the sensors I have connected to the board, and would like to automate the process better than manually commenting and uncommenting #defines. If I'm approaching this from the wrong angle I'm happy for any suggestions, thanks!

pert

The way you would do this is by setting global macros via -D compiler flags. This is done by setting special build properties via Arduino CLI's "--build-properties" option
https://arduino.github.io/arduino-cli/latest/commands/arduino-cli_compile/#options

So let's say you wanted to set a macro named "SENSOR_XYZ". You could do that like this:
Code: [Select]
arduino-cli compile --build-properties compiler.cpp.extra_flag=-DSENSOR_XYZ

This will result in the same thing as if you had added this line to every C++ file in the project (which includes the .ino files of sketches):
Code: [Select]
#define SENSOR_XYZ

Then in your sketch, you can do things like this:
Code: [Select]
#ifdef SENSOR_XYZ
// code for the XYZ sensor here
#endif


You can name your macro however you like, and also set it to specific values if needed.

For most uses, this should work perfectly well. There are a couple of potential problems that you might run into with more advanced usages of the "--build-properties" option:
  • Macro values containing quotes or commas are not supported. Both these bugs are in the process of being fixed right now: https://github.com/arduino/arduino-cli/pull/1044
  • 3rd party platform authors using the compiler.cpp.extra_flag for internal uses, even though it's intended to be free for use by the user. This is fairly rare, and won't happen if you are using an official Arduino board platform. There is a discussion about how this might be resolved here: https://github.com/arduino/arduino-cli/issues/846

tclambert00

This is exactly what I needed, thank you!

pert

You're welcome. I'm glad if I was able to be of assistance. Enjoy!
Per

Go Up