PlatformIO Community

Get Env Var in PlatformIO.ini?

I have set environment variables within python scripts so that I can use them in my source files. I know how to use a common section and refer to those settings in board-specific settings. What I am looking for is how I might set a platformio.ini value via the environment set by the python script.

Specifically, I have tried this:

  • Within build_flags specify a python file with !python script.py which sets an environment variable with print("-DPORT={0}".format("COM*))
  • Within platformio.ini, “read” that value when setting upload_port and monitor_port with something like upload_port = -DPORT

The end goal here is not having to edit the platformio.ini port values as we switch between a Mac and a Windows user. It seems to work fine with auto settings on Windows machines, but apparently, the developer on the Mac has to be more explicit.

  1. If Autodetect is not working properly on a Mac then there could either be an issue in the core (–> https://github.com/platformio/platformio-core/issues) or a problem with the developer’s device, if there e.g. exist multiple serial devices of which only one is e.g. functional (seen that with the CH340 driver mess for Mac OS from the chinese vendor and Apple drivers mixed in often enough in that forum)
  2. You can still manipulate the upload port in python logic by changing the UPLOAD_PORT entry in the environment object, e.g.
[env:uno]
platform = atmelavr
board = uno
framework = arduino
extra_scripts = get_port.py

in the platformio.ini with a get_port.py of

Import("env")
#print(env.Dump())
# fix upload port before upload
env["UPLOAD_PORT"] = "COM3"

you’ll see that that has indeed overridden PlatformIO’s automatic search

Looking for upload port...
Use manually specified: COM3
Uploading .pio\build\uno\firmware.hex

even though no upload_port = .. directive was directly in the platformio.ini.

Fantastic! Thank you, Max!