Go Down

Topic: Array of functions (addressing multiple identical sensors) (Read 1 time) previous topic - next topic

Tom Carpenter

I've come up with the following, which compiles. Not sure if this is the right way to go, or if it's garbage.
Code: [Select]

  for (int i=0; i<(maxDHT-1); i++) {
    Serial.print(i), Serial.print("\n");
    DHT aDHT(i, 11); //define a new DHT at pin i with type 11;
    myDHT[i]=&aDHT; // store pointer to aDHT in array myDHT at index i

The problem with that code is that the aDHT instances go out of scope at the end of the for loop and so the array of pointers will become invalid.


Hmmm -- I think I see where you got your Karma from.
It looks like it compiles without errors, now I have this, which compiles without errors:

Code: [Select]

#include <Arduino.h>
#include <DHT.h>

const int maxDHT = 5;
DHT* myDHT[maxDHT]; // array of 5 pointers to DHTs
// DHT aDHT(1,11); // dummy DHT with pin 1 and Type 11
float temp, humid;

void setup(){
 for (int i=0; i<(maxDHT-1); i++) {
   Serial.print(i), Serial.print("\n");
   myDHT[i] = new DHT(i, 11); //define a new DHT at pin 11;

void loop(){
 for (int i=0; i<(maxDHT-1); i++) {
   Serial.print(i), Serial.print(", T = "); Serial.print(temp); Serial.print("\n");
   Serial.print(i), Serial.print(", H = "); Serial.print(humid); Serial.print("\n");


Addendum -

So... contrary to many posts on the web, 'new' *does* exist in avr-gcc (under Arduino-1.0.1 in my case). That makes things a lot easier. It seems the latest version does indeed compile, and code size seems to scale with maxDHT:


Thanks for all your help, people!



So... contrary to many posts on the web, 'new' *does* exist

For a long time (prior to IDE version 1.0 I suspect), it didn't - hence the confusion caused by older discussions of the topic.


Why are you using 'i<(maxDHT-1)' everywhere? If maxDHT is the number of DHTs then the condition should be 'i < maxDHT'. If it isn't, then perhaps you should be defining some other constant which is.
I only provide help via the forum - please do not contact me for private consultancy.

Go Up