I have 8x AM2301 sensors which I can read individually using this DHT library and the example code modified to my requirement. This implies having to do something like this for each sensor (which results in a lot of repeating code).
DHT dht(DHTPIN, DHTTYPE);
dht.begin();
float t,h;
t = dht.readTemperature();
h = dht.readHumidity();
Now I am trying to refactor my code so that I have an array of DHT objects that I can iterate over to declare, initialize, and read the values from (into arrays of floats).
After checking out some threads on stackoverflow, etc. I came up with two versions of my code that compile.
Here is the relevant portion of my code. The entire source (PlatformIO based) is uploaded here.
SERIAL.print("Reading sensors: ");
uint32_t startTime = millis();
uint8_t SENSORS[] = { PIN_SENSOR0, PIN_SENSOR1, PIN_SENSOR2, PIN_SENSOR3,
PIN_SENSOR4, PIN_SENSOR5, PIN_SENSOR6, PIN_SENSOR7 };
SERIAL.println("INIT SENSORS");
/* Please disregard this snippet.
// I was trying various things before posting here and messed up.
DHT am2301[8];
uint8_t i;
for (i=0; i<8; i++){
*am2301[i] = DHT(SENSORS[i], DHT_TYPE);
am2301[i]->begin();
}
*/
// This locks up
DHT **am2301;
am2301 = new DHT* [8];
uint8_t i;
for (i=0; i<8; i++){
am2301[i] = new DHT(SENSORS[i], DHT_TYPE);
am2301[i]->begin();
}
However, both of these styles lock up the code execution just after printing "INIT SENSORS". The target platform is ATSAMD21.
I am not an expert C/C++ programmer, so there may be something I am missing or overlooking here. I need some help in trying to figure out what I am doing wrong, and if there is a better way to do this.
EDIT: Using vector as recommended in the accepted answer, I was able to have an iterable list of objects. However, the program still locks up. It seems this particular issue is related to the DHT library not liking multiple dynamic objects. Now off to github...
am2301[i]->begin();. I was trying out some different things just before posting this here, and messed up. At this point I just want an array of DHTs that I can init with (PIN_SENSORx, DHT_TYPE), and begin() and read from.