Search code examples
avresp8266nodemcuarduino-esp8266

How to programatically identify which microcontroller is connected to my computer


I recently bought a NodeMCU ESP8266 and started playing with it. Even though almost all the scripts I've written for Arduino micro controllers work fine on ESP8266, there are some differences. For example, reading from the EEPROM or using the internal VREF in my Esp8266.

I know that one can identify which Arduino board is connected using the following code:

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)

//Code in here will only be compiled if an Arduino Mega is used.

#elseif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)

//Code in here will only be compiled if an Arduino Uno (or older) is used.

#elseif defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega16U4__)

//Code in here will only be compiled if an Arduino Leonardo is used.

#endif 

However, this works for arduino micro controllers. How would I be able to do it for an esp8266 microcontroller?


Solution

  • Like you mentioned in your question, the #if defined(__xxxxx__) statements are not actually running on the microcontroller. They're preprocessor directives. The if statements decide which code to pass to the actual compiler, and which ones to omit.

    What you can do is write your code to read from the eeprom, but for the section of code that differs between microcontrollers (I'd recommend a separate function for each) you can choose between at compile time.

    For example

    #ifdef AVR_MICROCONTROLLER
    
    read_from_eeprom(...)
    {
      code for the avr chip
    }
    
    #else // I'm assuming there's no other options besides avr and esp
    read_from_eeprom(...)
    {
      code for esp chip
    }
    #endif
    

    Then when compiling, use a -D flag to specify that you are using AVR or omit the tag for esp.

    gcc ... -D AVR_MICROCONTROLLER ...
    

    I sense the reason you asked this question might stem from confusion about where the __AVR_ATmega1280__, etc... tags come from. Basically, they aren't keywords used by the compiler to decide which chip to compile for. They're created by the person(s) who wrote the source file, and they're used for portability so the same file can be used with many different platforms/processors. In my answer I used a command line tag to define the AVR_MICROCONTROLLER tag. Other projects (E.g. Marlin firmware running on arduinos) also have config files full of define statements that can be used to configure exactly how the code is compiled. Long story short, yes the same can be done for other microcontrollers, and you would do it by writing your own preprocessor if statements and then choosing which parameters/variables to set at compile time depending on the chip you want to run the code on.