我已经让所有代码都在阅读温度和湿度值,但是我在尝试正确编译和发布时遇到了很大困难。我有两个数组声明存储读数。 - 工作。我已成功连接到我的MQTT代理 - 工作。我可以打印到控制台 - 工作。对于我的生活,我似乎无法使用#include和#include来发布数据。这是发布循环,我将数据打印到控制台,并希望使用它来发布到我的8个不同的MQTT主题。
// MQTT Setup MQTT: ID, server IP, port, username and password
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#define MQTT_VERSION MQTT_VERSION_3_1_1
String sPayload;
char* cPayload;
String sTopic;
char* cTopic;
float pubtemp;
//This is the array for the topics
String station[8] ={
{"home/Front_Porch"},
{"home/Living_Room"},
{"home/Plant_Room"},
{"home/Office"},
{"appliances/Basement_Fridge"},
{"appliances/Basement_Freezr"},
{"appliances/Beer_Fridge"},
{"appliances/Pellet_Stove"}};
//These are the arrays for the variable readings
//Initialize the Temperature and Humidity Values
int Ch[8][2] = {{2120,00},{2120,00},{2120,00},{2120,00},{2120,00},{2120,00},
{2120,00},{2120,00}};
//This is the array for the low battery flag on the sensors
int Batt[8] = {0, 0, 0, 0, 0, 0, 0, 0}; // added 2/2/18 for battery status
这是执行发布的代码
if (now - lastSampleTime >= fiveMinutes)
{
lastSampleTime += fiveMinutes;
// Serial.print (lastSampleTime);
// Serial.println("***");
if (!client.connected()) {
reconnect();
}
for (int m=0; m <=7; m++){
Serial.print ("Channel ");
Serial.print (m);
Serial.print("\t");
for (int n=0; n<=1; n++){
if (n == 0) {
Serial.print ("Temp ");
// Serial.print (Ch[m][n]);
Serial.print ("\t");
float mytemp= (Ch[m][n]);
pubtemp=mytemp/10;
Serial.print (pubtemp,1);
Serial.print("\t");
}
else if (n == 1){
Serial.print ("RH ");
Serial.print("\t");
Serial.print (Ch[m][n]);
Serial.print("\t");
}
}
Serial.print (Batt[m]);
Serial.print ("\t");
Serial.print (station[m]);
Serial.println (" ");
//Insert code here to publish the MQTT data before the next brace
//This will publish a topic and associated data for each sensor
StaticJsonBuffer<200> jsonBuffer;
JsonObject& payload = jsonBuffer.createObject();
payload["temperature"] = pubtemp;
payload["humidity"] = Ch[m][1];
payload["batt"] = Batt[m];
/This formats the json for the data and is working
sPayload = "";
payload.printTo(sPayload);
cPayload = &sPayload[0u];
Serial.println (cPayload);
This is where I'm having difficulties with the variable topics
sTopic="";
client.publish(station[m],cPayload); This does not work.
}
//Publish a message when the full scan completes and this works
client.publish("outTopic","Scan Complete");
Serial.println ("Scan Complete");
}
数据的串行输出
json输出正在工作,主题正在打印,但我似乎无法使用client.publish {“topic”,“payload”)来处理变量主题