ESP32S/DHT22/ send data in JSON format to CloudMQTT
Posted: Thu May 02, 2019 4:06 pm
Hi guys! This is my problem:
I do the weather station using the DHT22 sensor. I have to send DHT22 data in JSON format to CloudMQTT.
You can see my code below. The problem is - I can send data in JSON format to the compilation window , but now to the CloudMQTT...please help me
I do the weather station using the DHT22 sensor. I have to send DHT22 data in JSON format to CloudMQTT.
You can see my code below. The problem is - I can send data in JSON format to the compilation window , but now to the CloudMQTT...please help me
Code: Select all
#include "ArduinoJson.h"
#include <PubSubClient.h>
#include <Wire.h>
#include <ETH.h>
#include <WiFi.h>
#include <WiFiAP.h>
#include <WiFiClient.h>
#include <WiFiGeneric.h>
#include <WiFiMulti.h>
#include <WiFiScan.h>
#include <WiFiServer.h>
#include <WiFiSTA.h>
#include <WiFiType.h>
#include <WiFiUdp.h>
#include "DHT.h"
#define SensorPin 16
#define SensorType DHT22
DHT Sensor(SensorPin, SensorType);
const char* ssid = "";
const char* password = "";
const char* Mosquitto_Server = "";
const int Mosquitto_port = ;
const char* user_mqtt = "";
const char* pass_mqtt = "";
WiFiServer server(80);
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
delay(100);
Sensor.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
Serial.println();
}
Serial.println("Connected to :");
Serial.println(ssid);
client.setServer(Mosquitto_Server, Mosquitto_port);
while (!client.connected()) {
Serial.println("Connecting to CloudMQTT...");
if (client.connect("ESP32Client", user_mqtt, pass_mqtt)) {
Serial.println("Connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
Serial.println("Sensor starts...");
}
void loop() {
float Hum = Sensor.readHumidity();
float Temp = Sensor.readTemperature();
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root ["esp/hum"] = Hum;
if (isnan(Temp) || isnan(Hum) ) {
Serial.println(F("Sensor Error!"));
return;
}
else {
client.publish ("esp/hum" , root);
root.printTo(Serial);
delay(9000);
}
}