Search code examples
arduinolibrariesarduino-esp8266esp32

Arduino - Select header for DHT Sensor Based on Chip (ESP32 vs ESP8266)


I'll start by saying I'm not a C++/Arduino expert but I've played enough with this issue and googled enough where I can't figure it out.

I have some Arduino code that is calling a sensor library file which then is calling the DHT library (https://github.com/RobTillaart/Arduino/tree/master/libraries/). There are two main versions of this library, one in DHTStable which maintains compatibility with AVR and ARM based chips and one in DHTLib which is optimized for AVR. I am compiling the same sketch for both a ESP8266 (which requires the DHTStable) and a ESP32 (which works better with the DHTlib).

Right now I compile and download to a ESP32 then when I'm done I move the DHTLib library out, copy the DHTStable in, then compile and download for the ESP8266. Few days or a week later I do this copying and pasting again.

In my sensor library I am already doing a check for the ESP32 for certain commands and if not a ESP32 I do the commands for a ESP8266 using #if defined(ARDUINO_ARCH_ESP32) and this works great for commands. However I am trying to use it for the defines and it "kinda" works. I have to take one of the two libraries and rename the header and cpp file along with all references internally to be different then the other. Then in my If I can do a if ESP32 use dht-avr.h (renamed) else dht.h (original).

This all works but I'm using git to clone and keep updated the libraries so each time there is a update I have to go through and rename everything. So I tried #include <DHTlib\dht.h> and <DHTStable\dht.h> but these don't work (can't find library).

Is what I want to do, calling the actual include path or two different headers when they are named identical, possible? Since the If statement works I'm 90% there (100% if I keep renaming everything) but I'd really like this to be automatic.

@BMelis put me on the right track with the .. in the path. The final code ended up being:

#ifdef ARDUINO_ARCH_ESP32
#include "..\DHTlib\DHT.h"
#else
#include "..\DHTStable\DHT.h"
#endif

Solution

  • An option would be to hardcode the path to the libraries in your code. You'll have to use quotation marks for the include instead of <...>:

    #ifdef ESP8266
    #include "../path/to/esp8266-header.h"
    #endif
    #ifdef ARDUINO_ARCH_ESP32
    #include "../path/to/esp32-header.h"
    #endif