Hi, i have a problem with simple flow with mqtt and two buttons (on and off)
I use pubsub client library and arduino.
My goal is to turn on/off led connected to esp8266 via nod red dashboard.
The problem is that in serial monitor allways have (msg onn) that turns always led on. If i press (off) button in dashboard the led turns off for a second or two and again turns on. (in serial monitor when peress off button it sends msg off but after that automatically recieves on msgs)
I paste the flows and the arduino code:
[{"id":"3440dee8.160c22","type":"mqtt out","z":"c5653a05.c28fb8","name":"","topic":"ledcontrol","qos":"","retain":"","broker":"661629f4.451408","x":440,"y":200,"wires":[]},{"id":"661629f4.451408","type":"mqtt-broker","z":"","name":"","broker":"test.mosquitto.org","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""}]
the arduino code is:
#include <ESP8266WiFi.h>
#include<PubSubClient.h>
const char* mqtt_server="test.mosquitto.org";
WiFiClient espclient;
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
pinMode(2,OUTPUT);
Serial.begin(115200);
Serial.print("connecting");
WiFi.begin("alicska","cska1948"); //SSID,PASSWORD
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println();
reconnect();
}
void callback(char* topic,byte* payload,unsigned int length1){
Serial.print("message arrived[");
Serial.print(topic);
Serial.println("]");
for(int i=0;i<length1;i++){
Serial.print(payload[i]);
}
if(payload[0]==49) digitalWrite(2,HIGH); //ASCII VALUE OF '1' IS 49
else if(payload[0]==50)digitalWrite(2,LOW);//ASCII VALUE OF '2' IS 50
Serial.println();
}
PubSubClient client(mqtt_server,1883,callback,espclient);
void reconnect(){
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
while(!client.connected()){
if(client.connect("ESP8266Client123456789")){
Serial.println("connected");
client.subscribe("ledcontrol");
}
else{
Serial.print("failed,rc=");
Serial.println(client.state());
delay(500);
}
}
}
void loop() {
if(!client.connected()){
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 5000) {
lastMsg = now;
}
}
Thank you for your help