esp32esp-idf

Environment variables on ESP32 chip?


Is there any way of setting an environment variable, or anything like an environment variable, when building an image for my ESP32 chip?

I know that I could bake my parameter into my program using a #define, but I would like to avoid rebuilding my whole program every time I change the value of this parameter.


Solution

  • Nvs is an option. But I think what the OP was really looking for was a quick way to switch a constant at build time, without having to edit the source code.

    One easy way is to use your CMakeLists.txt file to pass a local environment variable into your build:

    if(DEFINED ENV{MY_CONSTANT})
        add_compile_definitions(MY_CONSTANT=$ENV{MY_CONSTANT})
        message(STATUS "SETTING MY_CONSTANT TO : $ENV{MY_CONSTANT}")
    endif()
    

    N.B. Make sure you put this code above your project definition in the CMakeLists.txt file, or it won't work!

    And when you build the project, something like this:

    $ export MY_CONSTANT=100
    $ idf.py build
    

    or more likely in cmd.exe

    > set MY_CONSTANT=100
    > idf.py build
    

    Then inside the C code, it's dead simple:

    #ifdef MY_CONSTANT
        ESP_LOGE(TAG, "MY_CONSTANT = %d", MY_CONSTANT);
    #endif