I am using Arduino IDE to program an ESP8266, which is connected to a number of sensors. The end goal is to publish the sensor data via MQTT.
I have an array with sensor names:
const char* sensorIDArray[] = { // Used for the MQTT string
"DS18B20_1",
"DS18B20_2",
"DS18B20_3",
"DHT22_t",
"DHT22_h",
"Hygrometer_1",
"Hygrometer_1",
"Hygrometer_1",
"Hygrometer_1",
"Battery"
};
I have another array which is populated with some sensor readings:
float readingsArray[10]; //Saving the last measurement
/* Array element reminder:
*
* readingsArray[0] = DS18B20_1
* readingsArray[1] = DS18B20_2
* readingsArray[2] = DS18B20_3
* readingsArray[3] = DHT22_t
* readingsArray[4] = DHT22_h
* readingsArray[5] = Hygrometer_1
* readingsArray[6] = Hygrometer_2
* readingsArray[7] = Hygrometer_3
* readingsArray[8] = Hygrometer_4
* readingsArray[9] = Battery
*/
I am then trying to send the reading to a MQTT client by looping through each element of the array:
char readingVal;
for (int i = 0; i<10; i++) {
dtostrf(readingsArray[i], 7, 2, readingVal); //convert float to string
char* topic = "ESPlant/" + sensorIDArray[i]; //concatenate MQTT topic
client.publish(topic, readingVal); //publish MQTT topic and sensor reading
delay(10); //delay to ease burden on MQTT server.
}
I am new to C++ and Arduino in general. I am very confused by char, char* and arrays of both, despite many hours of googling. The client.publish is limited to a String only (!!!) for the argument readingVal above. The error message is:
invalid conversion from 'char' to 'char*' [-fpermissive]
readingValof typechar, when you are going to store a string in it? How do you expectchar* topic = "ESPlant/" + sensorIDArray[i]to work? - Arnav Borborahchar* topic = "ESPlant/" + sensorIDArray[i];-- This does not do concatenation in C++. To be honest with you, your issue has nothing to do with MQTT, Arduino, or anything else except, simple, basic, C++ that you will find in any textbook. - PaulMcKenziecharpointers, and you do not concatenate those using+. Seems as if you're trying to write C++ by using other computer languages as a guide. That never works. The proper way to concatenate strings is to either use a string class to represent strings that has overloaded operator+, or if using string literals and char arrays, usestrcat. But this should be covered in any good C++ tutorial, book, or website. - PaulMcKenzie