Why does DHT-library (and others) only allow one object instance? I came across the problem to handle two DHT22 devices. 

I use the Adafruit DHT Sensor library.

Since my Arduino sketch works as a "relay" for Serial commands on a host, I tried to wire up and dynamically instantiate DHT22. With no luck.

I checked the source and found, that the DHT object only gets constructed before setup() as a constant in the examples, because the library is written that way. 

I did a quick hack, which works, but seems ugly to me:

DHT.cpp

DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
-  _pin = pin;
-  _type = type;
-  #ifdef __AVR
-    _bit = digitalPinToBitMask(pin);
-    _port = digitalPinToPort(pin);
-  #endif
+  //_pin = pin;
+  //_type = type;
+  //#ifdef __AVR
+  //  _bit = digitalPinToBitMask(pin);
+  //  _port = digitalPinToPort(pin);
+  //#endif

...

-void DHT::begin(void) {
+void DHT::begin(uint8_t pin, uint8_t type, uint8_t count) {
+  _pin = pin;
+  _type = type;
+  #ifdef __AVR
+    _bit = digitalPinToBitMask(pin);
+    _port = digitalPinToPort(pin);
+  #endif


DHT.h*

-   void begin(void);
+   void begin(uint8_t pin, uint8_t type, uint8_t count=6);


Basically, I moved a few lines from the constructor to the begin() method. The whole thing works. I can even rewire &amp; change the data-pin dynamically while the Arduino runs.

Here are my questions:


Is the hacked away behavior a bug or feature?
Would my solution be good enough for a pull request to Adafruit? I would clean it up beforehand.
There is nothing wrong with the library. It does not allow just one object instance.

What is wrong is your way of using it.

It, and many other libraries, specify the pin numbers and other (under normal usage) static data in the constructor. You want to have two objects then create two objects.

But it seems you want to change that static data. So you need to construct differently.  Instead of statically declaring your objects you need to be dynamic. Use new and delete. 

DHT *myDHT = NULL;

myDHT = new DHT(4,5);
// do something
// change pins
delete myDHT;
myDHT = new DHT(6,7);