As I said four characters will not fit into your array and there you have four.
The potential for negatives may not be there in real life but since you don't check whether the sensor provides valid data via the result
you can never be certain to not get a negative reading or a reading > 99.9°C. Hence it does make sense to point out the fact.
A programmer has to expect the unexpected, even the impossible has to be considered!
Hard to tell, but one possibility is that the corrupting call affects some memory location which the Particle.publish()
call doesn't care about and may even rectify by being called (especially the state of the stack springs to mind).
When removing that call, the subsequent call may not be as resilient and crash.
While I could come up with several other possible explanations, there is little use in doing so, as it doesn't matter. Erroneous code needs to be corrected in any case, no matter why it crashes. It even needs correcting when it doesn't crash at all.
And I have suggested what to do
- use
snprintf()
- address the too small buffer problem
While at it, incorporate the other suggestions to adopt better coding practices.
This would be my take on this
#include <MQTT.h>
#include <PietteTech_DHT.h>
#include <DustSensor.h>
const char mqttADDR[] = "192.168.1.12";
const char mqttTOPIC[] = "photon";
const char mqttUSER[] = "User";
const char mqttPWD[] = "Pwd";
const char mqttINFO[] = "environment";
const int dhtTYPE = DHT22;
const int dhtPIN = D4;
const uint32_t msDELAY = 100;
float temp; // temperature in [°C]
float hum; // relative humidity in [%]
char envData[128]; // string for Particle.variable and MQTT publish
pms5003data pmsData;
MQTT client(mqttADDR, 1883, [](char* topic, byte* payload, unsigned int length) {}); // don't care to receive data (empty lambda)
PietteTech_DHT DHT(dhtPIN, dhtTYPE);
DustSensor dustSensor;
void setup() {
dustSensor.begin();
Particle.variable(mqttINFO, envData);
client.connect(mqttTOPIC, mqttUSER, mqttPWD);
}
void loop() {
static uint32_t ms = 0;
if (millis() - ms < msDELAY) return;
ms = millis();
readDHT();
readPMS5003();
publishData();
}
int readDHT() {
int result = DHT.acquireAndWait(2000);
if (result >= DHTLIB_OK) {
temp = DHT.getCelsius();
hum = DHT.getHumidity();
result = DHTLIB_OK;
}
return result;
}
int readPMS5003() {
if(dustSensor.listen()) {
pmsData = dustSensor.readData();
return 0;
}
return -1;
}
void publishData() {
snprintf(envData, sizeof(envData)
, "{ \"temp\": %.1f, \"rh\": %.1f, \"pm10\": %u, \"pm25\": %u, \"pm100\": %u }"
, temp
, hum
, pmsData.pm10_standard
, pmsData.pm25_standard
, pmsData.pm100_standard
);
if (client.isConnected()) {
client.publish(mqttINFO, envData);
}
else {
client.connect(mqttTOPIC, mqttUSER, mqttPWD);
}
}