Toggle Led with cloudMqtt and Homeassistant and NodeMCU

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 &amp; 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

You need to get your esp8266 to subscribe to the topic being sent, so that the callback is called.
Try

 if (client.connect(mqtt_server, mqtt_user, mqtt_password)) {
  Serial.println(“connected”);
  client.subscribe("home1/bedroom/switch1/set");
}

Ok thanks a lot.
And another thing
Is the line
String receivedChar = (String)payload[i];
Correct ??

Because i want to define my payload as a string.
For example i have 2 switches and i want to set different payload on theme
Like switch1-on ,switch1-off ,switch2-on,switch2-off

But i dont know how should i do that

It looks like the for ... loop construct isn’t doing what you expect.

It is taking each character in turn from the payload and comparing it to a whole string.

I do this to convert my topic and payload to strings, which I undoubtedly copied from someone else

  // Allocate the correct amount of memory for the payload copy
  byte* p = (byte*)malloc(length);
  // Copy the payload to the new buffer
  memcpy(p,payload,length);
  
  // Conversion to a printable string
  p[length] = '\0';
  String payload_s = String((char *) p);
  String topicNameRec = String((char*) topic);
  
  // Process the message using `topicNameRec` and `payload_s`

  // Free the memory
  free(p);
1 Like

Ok

Thanks a lot

I will check it.

Hi again

I made some changes to my code but it doesn’t work again

indent preformatted text by 4 spaces

#include “DHT.h”
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

void callback(char* topic, byte* payload, unsigned int length);

const char* ssid = “***";
const char* password = "***";
const char
mqtt_server = “m11.cloudmqtt.com”;
const int mqtt_server_port = ;
const char
mqtt_user = “switch1”;
const char
mqtt_password = "
”;
const int switchPin1 = 5;

char const* switchTopic1 = “/house/switch1/”;

WiFiClient wifiClient;

PubSubClient client(mqtt_server, mqtt_server_port,callback,wifiClient);

void setup(void)
{
pinMode(switchPin1, OUTPUT);

digitalWrite(switchPin1, LOW);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("\n\r \n\rConnecting to ");
Serial.println(ssid);

// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n\rESP8266 &amp; 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”);
client.subscribe(switchTopic1);
} 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()
{
client.loop();
}

void callback(char* topic, byte* payload, unsigned int length) {
String topicStr = topic;
Serial.println(“Callback update.”);
Serial.print("Topic: ");
Serial.println(topicStr);
if (topicStr == “/house/switch1/”)
{

if(payload[0] == '1'){  
  
 digitalWrite(switchPin1, HIGH);  
       
 client.publish("/house/switchConfirm1/", "1");  
 delay(700);  
 }  

 
  
else if (payload[0] == '0'){  
  
 digitalWrite(switchPin1, LOW);  
       
 client.publish("/house/switchConfirm1/", "0");  
   
 }  
 } 
}  
indent preformatted text by 4 spaces

and i write these things in my configuration.yaml file:

switch 1:

  • platform: mqtt
    name: “Wall Light”
    state_topic: “/house/switchConfirm1/”
    command_topic: “/house/switch1/”
    payload_on: “1”
    payload_off: “0”
    qos: 0
    retain: true

and i see in the serial monitor and my cloud mqqt logs that messages send and receive successfully but the LED didn’t turn on/off.

I dont know where is the problem???

Can you see if this is getting sent? If so, the problem is with the digitalWrite() or the hardware, and I can’t help much with that.

Yes I see this