Hi Guys
I have created a mqtt switch in my home assistant panel and when i toggle the switch it sends messages to cloudmqtt properly.
But I want to send this messages to nodeMCU too and print it to serial monitor but i cant
indent preformatted text by 4 spaces
#include “DHT.h”
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
float humidity, temp_f;
const char* ssid = “Amir”;
const char* password = “911183012”;
const char* mqtt_server = “m11.cloudmqtt.com”;
const int mqtt_server_port = 18749;
const char* mqtt_user = “switch1”;
const char* mqtt_password = “09393721211”;
int ledPin = 1;
String message="";
DHT dht2(2,DHT22);
WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print(“Message arrived [”);
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++)
{
String receivedChar = (String)payload[i];
Serial.print(receivedChar);
if (receivedChar == “OFF”)
{
digitalWrite(ledPin, HIGH);
}
if (receivedChar == “ON”)
{
digitalWrite(ledPin, LOW);
}
}
Serial.println();
}
PubSubClient client(mqtt_server, mqtt_server_port,wifiClient );
void setup(void)
{
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("\n\r \n\rConnecting to ");
Serial.println(ssid);
client.setCallback(callback);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n\rESP8266 & DHT22 based temperature and humidity sensor working!");
Serial.print("\n\rIP address: ");
Serial.println(WiFi.localIP());
while (!client.connected()) {
Serial.print("Attempting MQTT connection to “);
Serial.print(mqtt_server);
Serial.print(” ");
// Attempt to connect
if (client.connect(mqtt_server, mqtt_user, mqtt_password)) {
Serial.println(“connected”);
} else {
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop()
{
// temp_f = dht2.readTemperature();
// message = “{“temp”: “” + String((int)temp_f) + “”}”;
//Serial.println("Temperature in C:");
//Serial.println((dht2.readTemperature( )));
//Serial.println("Humidity :");
//Serial.println((dht2.readHumidity( )));
//client.publish("/dht", message.c_str());
client.loop();
}
Here is my code.
and I recieve the messages in the cloudmqtt like this pic.
The last one is for switch