Obscure Arduino tips #1

Want to know exactly which ESP8266 board your sketch is compiled for in the Arduino IDE and act on that in your sketch?

Why do I need this? I'm building for a couple of different flavours of ESP8266 boards and wanted to know which board is the target so I can change a value to match the board automatically.

I'm using the ESP8266 core as an example but this should also apply to other boards supported in the Arduino IDE with some tinkering.

  • Find the file 'boards.txt' in ESP8266 Arduino core. On Windows this will be somewhere like "C:\Users\YOUR USERNAME\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.2\boards.txt"
  • Search for the name of your board as shown in the Arduino IDE, for example "LOLIN(WEMOS) D1 mini Pro". You should find a line that looks like "d1_mini_pro.name=LOLIN(WEMOS) D1 mini Pro"
  • Immediately below this there should be line similar to "build.board=ESP8266_WEMOS_D1MINIPRO".
  • The compiler passes the build.board value on as a #define but it prepends "ARDUINO_".
  • So if "ARDUINO_ESP8266_WEMOS_D1MINIPRO" is defined in your code you know it has been compiled for a Wemos D1 mini pro.
I am using this so I can do a readVcc() and get an accurate value for Vcc across a couple of different flavours of module. Here's a usable code fragment...


float vcc()
{
  uint16_t v = ESP.getVcc();
  #ifdef ARDUINO_ESP8266_WEMOS_D1MINI
    return((float)v/918.0f);
  #else
    #ifdef ARDUINO_ESP8266_WEMOS_D1MINIPRO
      return((float)v/918.0f);
    #else
      #ifdef ARDUINO_ESP8266_GENERIC
        return((float)v/1024.0f);
      #endif
    #endif
  #endif
}

The slightly different values are because the boards have a slightly different set of resistors on the Vcc monitoring connection and these are the values I've found generate realistic readings verified by a meter.

The IDE also sets the environment variable ARDUINO_BOARD, which you can use, for example...

Serial.print(ARDUINO_BOARD);


You could use this to avoid wading through boards.txt, or code the above example differently.

No comments: