Hi all,
I have a product that has a DHT22 sensor in it.
I had to deploy one without the right sensor, and I installed a DHT11.
It works fine if I redefine the dht type and pin.
Can I make the #define statement conditional?
Something to the effect of:
if (dht11) {
#define DHTPIN C0 // what pin we're connected to
#define DHTTYPE DHT11
}
else {
#define DHTPIN D3 // what pin we're connected to
#define DHTTYPE DHT22
}
#define instructions are preprocessor instructions that have no business inside the active code.
As the name suggests, the pre-processor runs before the actual compiler run and after the preprocessor has done its job the instructions will just vanish.
Consequently your code will look like this for the compiler
if (dht11) {
// what pin we're connected to
}
else {
// what pin we're connected to
}
Usually your code has a block like this at the top which defines how the code should be compiled.
Consequently your dht object is already constructed with exactly these parameters, and if you want to change them, you’d need to destroy the object and re-construct it with the new settings.
One would be to instantiate the dht object at run time depending on a state of a pin or set some flag that can be stored in EEPROM which would be read on startup.
OK, so do I just use something like this to instantiate the dot object later on in code, say in the setup loop based on my EEPROM flag? And then I avoid using any #define statements
Something like that.
But since you can only instantiate an object inside a function, you'd need to have a global variable which you only set.
The way you wrote it there would only create a local object that'd vanish once you leave the function.
I'd declare a global DHT* dht; and then set it as needed via dht = new DHT(2, DHT22); and when calling any methods on it, it would be done this way dht->begin();.
BTW
setup() is a function not a loop. loop() as also a function and it's name suggests that it behaves somehow like a loop (being called over and over).